类似于三数之和,首先排序,确定前两位之和用双指针确定后两位,注意重复问题的解决。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<vector<int>>ans;
if (n < 4)return {};
for (int i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < n - 2; j++) {
if (j > i+1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1;
int right = n - 1;
while (left < right) {
if ((long)nums[i] + nums[j] + nums[left] + nums[right] > target) {
right--;
}
else if ((long)nums[i] + nums[j] + nums[left] + nums[right] < target) {
left++;
}
else {
ans.push_back({ nums[i],nums[j],nums[left],nums[right] });
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
left++;
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
right--;
}
}
}
}
return ans;
}
};
int main() {
Solution test;
vector<int>s = { 1000000000,1000000000,1000000000,1000000000};
vector<vector<int>>ans = test.fourSum(s,0);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j]<<",";
}
cout << endl;
}
}