TwoSum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

 

Subscribe to see which companies asked this question

 
解题报告:
扫描给定列表,判断target与扫描到的元素是否出现在自己新建的字典中。如果有,则返回各自下标。如果没有,将该元素加入字典中。
 1 class Solution(object):
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         d = {}
 9         for i in range(len(nums)):
10             if target - nums[i] in d:
11                 return [d[target-nums[i]], i]
12             else:
13                 d[nums[i]] = i

 

posted on 2016-07-10 14:20  stackhacks  阅读(173)  评论(0编辑  收藏  举报

导航