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
过还是挺容易的,从头到尾,挨个算,这是方法一,见注释。不过这样显然更慢
方法二,用hash
map记录,它存储的值很重要,应该 这样存储 : map[target - nums[i]] = i
class Solution(object):
def twoSum(self, nums, target):
#using hash
map = {}
for i in xrange(len(nums)):
#print map.items()
if nums[i] not in map:
map[target - nums[i]] = i
else:
return [map[nums[i]],i]
'''
for i in xrange(len(nums)):
if target - nums[i] in nums[i+1:]:
return [i,i + 1 + nums[i+1:].index(target - nums[i])]
'''