题目
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 用键做下标来寻值
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来寻值是常数级的,不用遍历;
② 注意map的寻值和插入方法