classSolution(object): deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ index = 0 ret = [] ok = False for index in range(len(nums)): other = target - nums[index] start = index while start < len(nums) - 1: if nums[start + 1] == other: ret.append(index) ret.append(start + 1) ok = True break start += 1 if ok: break return ret
简便解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ num_map = {} index = 0 for num in nums: other = target - num if num_map.get(other) isnotNone: # 注意0 return [num_map.get(other), index] num_map[num] = index index += 1 return [0, 0]