暴力解法
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
vector<int>res;
for(int i=0;i<nums.size()-1;i++)
{
int temp=nums[i];
for(int j=i+1;j<nums.size();j++)
{
if(temp+nums[j]==target)
{
res.push_back(temp);
res.push_back(nums[j]);
}
}
}
sort(res.begin(),res.end());
return res;
}
};
双指针解法
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
vector<int>res;
int i=0,j=nums.size()-1;
while(i<j)
{
while(j>=0&&nums[i]+nums[j]>target) j--;
if(nums[i]+nums[j]==target)
{
res.push_back(nums[i]);
res.push_back(nums[j]);
break;
}
i++;
}
return res;
}
};