Leetcode 1.两数之和
Leetcode 1.两数之和
题目思路:使用一个哈希表,记录值和下标对应的关系,遍历整个数组,如果map中,存在target-nums[i],就得到了答案,否则就把该元素插入到map中
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++)
{
if(m.count(target -nums[i]))
{
res.push_back(i);
res.push_back(m[target - nums[i]]);
return res;
}
else m[nums[i]] = i;
}
return res;
}
};