哈希应用
作者:
巷港
,
2022-03-09 23:56:52
,
所有人可见
,
阅读 147
用unordered_map
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
unordered_map<int,int>hash;
for (int i=0;i<nums.size();i++)
{
if (hash[target-nums[i]]==0) hash[nums[i]]++;
else return {nums[i],target-nums[i]};
}
}
};
纯暴力
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
for (int i=0;i<nums.size()-1;i++)
{
for (int j=i+1;j<nums.size();j++)
{
if (nums[i]+nums[j]==target)
return {nums[i],target-nums[i]};
}
}
}
};