主要题意:
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
找到求和对应的索引。
最开始暴力求解:
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
for idx_1,each_1 in enumerate(numbers):
for idx_2,each_2 in enumerate(numbers):
if idx_1<idx_2:
if (each_1+each_2)==target:
return [idx_1+1,idx_2+1]
然而超时了!复杂度:O(n2)
于是借鉴了三种方法:
方法1:binary search
复杂度O(logn)