AcWing 75. 和为S的两个数字
原题链接
简单
作者:
mui
,
2020-04-06 04:29:59
,
所有人可见
,
阅读 532
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int i = 0, j = nums.size() - 1;
while (i < j && nums[j] > target) --j;
while (i < j)
{
int res = nums[i] + nums[j] - target;
if (!res) return {nums[i], nums[j]};
else if (res > 0) --j;
else ++i;
}
return {};
}
};
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
unordered_set<int> set {};
for (auto &i : nums) {
if (set.count(target-i) > 0) return {target-i, i};
if (set.count(i) == 0)
set.insert(i);
}
return {};
}
};