问题:
输入整型数组,返回两元素的索引,使得这两个元素之和为特定的结果。假设这两个元素为不同元素。
例如: nums = [1,3,2,7] , target = 5
返回[1,2], 因为nums[1] + nums[2] = 3 + 2 = 5; 当没有符合元素时, 返回null
def two_sum(li, target): dic = {} for index, val in enumerate(li): if target-val in dic: return [dic[target-val], index] else: dic[val] = index if __name__ == '__main__': print(two_sum([1,3,2,7], 5))
后续v2版本:双指针法,前提是数组必须有序
def two_sum_v2(li, target): left = 0 right = len(li)-1 while left <= right: sum = li[left] + li[right] if sum == target: return [left, right] elif sum < target: left += 1 else: right -= 1