和之前的3Sum和3SumCloset是一个思路,随便写写就行。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int len = size(nums);
sort(nums.begin(),nums.end());
vector<vector<int>> re;
if (len < 4 || nums[0]>0 || nums[len - 1] < 0) return re;
if (len == 4) {
if (nums[0] + nums[1] + nums[2] + nums[3] == target) re.push_back(nums);
return re;
}
int mar_l = 0;
int mar_r = len - 1;
for (; mar_l < len-1; mar_l++) {
if (mar_l>0&&nums[mar_l-1] == nums[mar_l])continue;
mar_r = len - 1;
for (; mar_l < mar_r; mar_r--) {
if (mar_r<len-1&&nums[mar_r+1] == nums[mar_r])continue;
int in_l = mar_l + 1;
int in_r = mar_r - 1;
int temp_mar = -(nums[mar_r] + nums[mar_l]) + target;
while (in_l != in_r&& in_l < in_r) {
int temp_in = nums[in_l] + nums[in_r];
if (temp_in == temp_mar) {
re.push_back({ nums[mar_l],nums[in_l],nums[in_r],nums[mar_r] });
in_l++;
in_r--;
while (in_l<in_r && nums[in_l - 1] == nums[in_l]){
in_l++;
}
while (in_l<in_r && nums[in_r + 1] == nums[in_r]){
in_r--;
}
}
else if (temp_in > temp_mar) {
in_r--;
}
else {
in_l++;
}
}
}
}
return re;
}
};