AcWing 75. 和为S的两个数字
原题链接
简单
普通双指针
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int sum) {
vector<int> res;
for(int i=0;i<nums.size();i++){
int j=i+1;
for(;j<nums.size();j++){
if(nums[i]+nums[j]==sum){
res.push_back(nums[i]);
res.push_back(nums[j]);
return res;
}
}
}
return {};
}
};
对撞双指针
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();){
for(int j=nums.size()-1;i<j;){
if(nums[i]+nums[j]<target) i++;
else if(nums[i]+nums[j]>target) j--;
else if(nums[i]+nums[j]==target){
nums.clear();
nums.push_back(nums[i]);
nums.push_back(nums[j]);
return nums;
}
}
}
return {};
}
};