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;
實例步驟如下: