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循環就能做出來,但是時間太長
//Solution1
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
int i, j;
for (i = 0; i < nums.size(); i++) {
for (j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
result.emplace_back(i);
result.emplace_back(j);
return result;
}
}
}
return result;
}
};
後來也是看了其他人的解法,發現用HashMap的思想會比較快。於是用了Python的字典dict{}
#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;
實例步驟如下: