Python解Leetcode: 1. Two Sum
- 
题目描述:求出数组中等于目标值的两个数的索引,假定肯定存在两个数并且同一个索引上的数不能用两次。 
- 
思路: 
- 用空间换时间,使用一个字典存储已经遍历的数字的索引,如果新遍历的数字和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   

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号