力扣第一题(哈希表)
题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。
但是,你不能重复利用这个数组中同样的元素。
一组数据,两次循环的情况下考虑使用哈希表,减少时间复杂度。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
m[nums[i]] = i; //先遍历一遍数组,建立HashMap映射
}
//然后再遍历一遍,开始查找,找到则记录index
for (int i = 0; i < nums.size(); ++i) {
int t = target - nums[i];
if (m.count(t) && m[t] != i) {//if里面的条件用于判断查找到的数字不是第一个数字
res.push_back(i);
res.push_back(m[t]);
break;
}
}
return res;
}
};