題目:
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 same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解題思路:
判斷數(shù)組 nums 中是否存在 2 個(gè)數(shù)組元素之和等于給定的 target 的值
- 我們可以使用一個(gè) map 來(lái)保存數(shù)組的信息,這個(gè) map 的 key 是 nums 數(shù)組的元素值, value 是 nums 數(shù)組的索引
- 迭代數(shù)組 nums 的元素值笆檀,將 target 值減去 nums 數(shù)組的元素值,得到 taget - nums[i]
- 判斷 map 中是否存在 key 為 taget - nums[i] 的 map全肮,若是存在取出 key 為 taget - nums[i] 的值
解題代碼:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
vector<int> retArray;
for (int i = 0; i < nums.size(); i++) {
map[nums[i]] = i;
}
for (int i = 0; i < nums.size() ; i++) {
int value = target - nums[i];
if (map.count(value) > 0 && map[value] != i) {
retArray.push_back(i);
retArray.push_back(map[value]);
break;
}
}
return retArray;
}
};