// //unordered_map的模板
// template<class key,
// class T,
// class Hash=hash<key>,
// class Pred = equal_to<key>,
// class Alloc = allocator<pair<const key,T>>
// unordered_map::allocator_type
// > class unordered_map;
// //主要使用的是模板中的前两个参数<键,值>
// unordered_map<const Key, T> map
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//暴力双层for循环
// for(int i=0;i<nums.size();i++){
// for(int j=i+1;j<nums.size();j++){
// if(nums[i]+nums[j] == target){
// return {i,j};
// }
// }
// }
//哈希法:查询一个元素是否出现过,或者一个元素是否在集合里,考虑哈希法
std::unordered_map<int,int>map;//unordered_map的键值对分别表示需要遍历的值,和该值在数组中对应的下标
for(int i=0;i<nums.size();i++){
//遍历当前元素,并在map中寻找是否有匹配的key
auto iter = map.find(target-nums[i]);
if(iter!=map.end()){//iter值符合条件,并且在map中找到target-num[i]值
return {iter->second,i};
}
//如果没找到匹配对,就把访问过的元素和下标加入到map中
map.insert(pair<int,int>(nums[i],i));
}
return {};
}
};
题目:
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
// //unordered_map的模板
// template<class key,
// class T,
// class Hash=hash<key>,
// class Pred = equal_to<key>,
// class Alloc = allocator<pair<const key,T>>
// unordered_map::allocator_type
// > class unordered_map;
// //主要使用的是模板中的前两个参数<键,值>
// unordered_map<const Key, T> map