1. 程式人生 > >leetcode 1-Two Sum python

leetcode 1-Two Sum python

one-pass Hash Table

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i in range(len(nums)):
            complement = target - nums[i]
            if(complement in d and d[complement] != i):
                return [d[complement], i]
            d[nums[i]] = i					

d[nums[i]] = i 這條語句必須放在後面.因為當前元素的目標元素在dict中,若不在,當前元素再放入dict中.若放在前面可能出現當前元素和目標元素相等後,當前元素更新dict中目標元素,導致無解 如:[3,3]