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].看题目的意思,只要找出两个数相加等于target就行了。
再看提示有哈希,那就用哈希吧,在python中,哈希就是个字典。试了一下,我用nums的值当key,target-nums[i]的值当value,下面贴代码
- class Solution(object):
- def twoSum(self, nums, target):
- """
- :type nums: List[int]
- :type target: int
- :rtype: List[int]
- """
- mDict = {}
- for i in range(len(nums)):
- if mDict.has_key(nums[i]):
- return [nums.index(mDict[nums[i]]),i]
- else:
- mDict[target - nums[i]] = nums[i]
- del mDict
- 其实很简单,大家可以看着代码体会一下,文字不是很好表达。