https://leetcode-cn.com/problems/two-sum/description/
給定一個整數(shù)數(shù)組和一個目標(biāo)值遥皂,找出數(shù)組中和為目標(biāo)值的兩個數(shù)逗堵。
你可以假設(shè)每個輸入只對應(yīng)一種答案秉氧,且同樣的元素不能被重復(fù)利用眷昆。
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1].
主要思路:
- 使用hashmap存儲每個數(shù)組元素相應(yīng)下標(biāo)<key=array_value, value=array_index>蜒秤。
- 遍歷數(shù)組,查找target - current_value是否已存在在hashmap中亚斋。存在則返回當(dāng)前元素和在hashmap查到的元素相應(yīng)下標(biāo)作媚,否則將<current_value, current_index>添加到hashmap。
代碼實現(xiàn):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashmap;
for (size_t i = 0; i < nums.size(); ++i) {
int current = nums[i];
if (hashmap.find(target - current) != hashmap.end()) {
vector<int> result;
result.push_back(hashmap[target - current]);
result.push_back(i);
return result;
} else {
hashmap[current] = i;
}
}
return vector<int>();
}
};