算法练习:四数之和
题目链接:. - 力扣(LeetCode)
这里利用双指针来控制:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(),nums.end());
vector<vector<int>> ret;
for(int a = 0;a < n;)
{
long long sum = target - nums[a];
for(int b = a+1;b < n; )
{
int left = b+1,right = n-1;
long long sum1 = sum - nums[b];
while(left < right)
{
long long add = nums[left] + nums[right];
if(add == sum1)
{
ret.push_back({nums[a],nums[b],nums[left],nums[right]});
left++;
right--;
while(nums[left] == nums[left-1] && left < right) left++;
while(nums[right] == nums[right+1] && left < right) right--;
}
else if(add<sum1) left++;
else right--;
}
b++;
while(b < n && nums[b] == nums[b-1]) b++;
}
a++;
while(a < n && nums[a] == nums[a-1]) a++;
}
return ret;
}
};