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, and you may not use the sameelement twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
这题不难,首先想到的就是暴力遍历,用两个for循环就能做出来,但是时间太长。时间复杂度为O(n^2)。
后来也是看了其他人的解法,发现用HashMap的思想会比较快。最坏情况为O(n)。
C++版:
Python版:
#Solution2
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
dic = {}
for x in range(n):
a = target - nums[x]
if nums[x] in dic: #关键步骤
return dic[nums[x]], x
else:
dic[a] = x;
实例步骤如下: