题目
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].
**
思路
**
建立哈希表,在遍历数组建立哈希表的时候就可以进行查找了,若找到goal,证明数据已经存在,只需要在返回查找到的值在数组中的下标值和当前遍历数组的位置即可
**
解答
**
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.size()<2) return vector<int>{};
map<int,int> nums_map;
vector<int> res_vec;
for(int i = 0; i<nums.size(); i++){
int goal = target - nums[i];
if(nums_map.end()!= nums_map.find(goal)){
res_vec.emplace_back(nums_map[goal]);
res_vec.emplace_back(i);
break;
}else{
nums_map[nums[i]] = i;
}
}
return res_vec;
}