这道题我要学习的地方有很多,比如
1**.auto:它是让编译器让它自动猜类型,适用于类型名称很长的适合,在这段代码中,x的类型如果不写成auto的话就写成unordered_map<int,int>::iterator(iterator是迭代器的意思)**
2.当返回值类型是vector<int>时,我们的return可以写成{i,x->second}这是列表初始化的写法
记住的方法是:
return{a,b}
自动打包成a和b,拼成题目想要的数组答案直接返回
3.x->second这个是代表哈希表中值x->first代表的是键
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>hash;
for(int i=0;i<nums.size();i++){
auto x=hash.find(target-nums[i]);
if(x!=hash.end()){
return {i,x->second};
}
hash[nums[i]]=i;
}
return {};
}
};
