首页 > 技术文章 > Two Sum [easy] (Python)

boluo007 2018-06-01 14:02 原文

由于题目说了有且只有唯一解,可以考虑两遍扫描求解:第一遍扫描原数组,将所有的数重新存放到一个dict中,该dict以原数组中的值为键,原数组中的下标为值;第二遍扫描原数组,对于每个数nums[i]查看target-nums[i]是否在dict中,若在则可得到结果。 
当然,上面两遍扫描是不必要的,一遍即可,详见代码。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        keys = {}
        for i in xrange(len(nums)):
            if target - nums[i] in keys:
                return [keys[target - nums[i]], i]
            if nums[i] not in keys:
                keys[nums[i]] = i

 

推荐阅读