18. 4 Sums
题目链接:18. 4Sums
题意
给出一个数组,求出该数组中所有和为给定值的四元组的集合
解法
4个变量比较难控制,受第15题3Sums的启发,结合分而治之的思想,可以遍历给定数组,每次相当于固定了第一个数,对后面的部分使用3Sums解法,算法时间复杂度为O(n^3)
代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
int len = nums.size();
sort(nums.begin(), nums.end());
if (len<4||4*nums[0]>target||4*nums[len-1]<target)
return result;
for (int i = 0; i <= len - 4; ++i) {
if (i > 0 && nums[i - 1] == nums[i])
continue;
if (4 * nums[i] > target) {//too large
break;
}
else if (nums[i] + 3 * nums[len - 1] < target) {//too small
continue;
}
theRestThree(nums, result, target - nums[i], nums[i], i);
}
return result;
}
void theRestThree(vector<int> &nums, vector<vector<int>> &result, int target, int first, int index) {
int len = nums.size();
if (len - index - 1 < 3 || 3 * nums[index + 1] > target || 3 * nums[len - 1] < target)
return;
int current, left, right, temp;
for (current = index + 1; current <= len - 3; ++current) {
if (current > index + 1 && nums[current - 1] == nums[current]) {//avoid duplication
continue;
}
if (3 * nums[current] > target) {//too large
break;
}
else if (nums[current] + 2 * nums[len - 1] < target) {//too small
continue;
}
left = current + 1;
right = len - 1;
while (left < right) {
temp = nums[current] + nums[left] + nums[right];
if (temp < target) {
++left;
}
else if (temp > target) {
--right;
}
else {
result.push_back({ first,nums[current],nums[left],nums[right] });
temp = nums[left];
while (left < right&&nums[left] == temp)
++left;
temp = nums[right];
while (left < right&&nums[right] == temp)
--right;
}
}
}
}
};
要点
- 分而治之:将4个变量固定一个,简化为3个变量的问题