AcWing 75. 和为S的两个数字
原题链接
简单
作者:
SayYong
,
2024-10-19 09:35:55
,
所有人可见
,
阅读 3
暴力解法
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
return vector<int>{nums[i], nums[j]};
}
}
}
return vector<int>{-1, -1};
}
};
哈希查找
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
unordered_set<int> hash;
for (int i = 0; i < nums.size(); i++) {
if (hash.count(target - nums[i])) return vector<int> {nums[i], target-nums[i]};
else hash.insert(nums[i]);
}
return vector<int>{-1, -1};
}
};