題目
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].
頻度: 5
解題之法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::map<int, int> my_map;
vector<int> result;
for(int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
//if numberToFind is found in map, return them
if(my_map.find(complement)!=my_map.end()){
result.push_back(i);
result.push_back(my_map[complement]);//map 用鍵做下標(biāo)來尋值
return result;
}
//number was not found. Put it in the map.
//my_map.insert(i,nums[i]);
// or say
//my_map.insert(pair<int,int>(i,nums[i]));
//my_map.insert(i, nums[i]);
my_map.insert(pair<int, int>(nums[i], i));
}
return result;
}
};
分析
① 用map來尋值是常數(shù)級的案糙,不用遍歷六水;
② 注意map的尋值和插入方法