Python解Leetcode: 1. Two Sum

  • 题目描述:求出数组中等于目标值的两个数的索引,假定肯定存在两个数并且同一个索引上的数不能用两次。

  • 思路:

  1. 用空间换时间,使用一个字典存储已经遍历的数字的索引,如果新遍历的数字和target的差值在字典中,则就是结果。
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dicts = {}
        for k, v in enumerate(nums):
            if target - v in dicts:
                return [dicts.get(target-v), k]
            dicts[v] = k   
posted @ 2017-12-04 22:12  潇湘旧友  阅读(251)  评论(0编辑  收藏  举报