LeetCode 筆記 - 167. Two Sum II - Input Array Is Sorted

題目在此 167. Two Sum II - Input Array Is Sorted

給一個 Sorting 過的數列,請找出兩個相加等於 target 的 index

解題思維

這題是 Two Pointers 大法的應用
不斷調整夾擠出最終結果

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:

left = 0
right = len(nums) - 1

while left < right:
value = nums[left] + nums[right]
if value == target:
return [left + 1, right + 1]
if value < target:
left += 1
else:
right -= 1

相關文章