連結

167. Two Sum II - Input Array Is Sorted
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/


一開始思考方向不能是從前面慢慢找,因為是有排序的,而且會有重複的,所以可以使用從頭尾找的方式

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def twoSum(self, numbers, target):
start_point=0
end_point=-1
for index, val in enumerate(numbers):
if target < numbers[start_point]+numbers[end_point]:
end_point-=1
elif target > numbers[start_point]+numbers[end_point]:
start_point+=1
return start_point+1,len(numbers)+end_point+1

神人解答

1
2
3
4
5
6
7
class Solution(object):
def twoSum(self, numbers, target):
dic = {}
for i, n in enumerate(numbers):
if n in dic:
return [dic[n]+1, i+1]
dic[target-n] = i