四数之和
给定一个包含n个整数的数组nums和一个目标值target,判断nums中是否存在四个元素a,b,c和d ,使得a + b + c + d的值与target相等?找出所有满足条件且不重复的四元组。
注意:答案中不可以包含重复的四元组。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [], target = 0
输出:[]
提示:
- 0 <= nums.length <= 200
- -109 <= nums[i] <= 109
- -109 <= target <= 109
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <iostream> #include <vector> #include <algorithm> using namespace std;
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> results; if (nums.size() < 4) { return results; } sort(nums.begin(), nums.end()); int len = nums.size(); for (int i = 0; i < len - 3; ++i) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) { break; } if (nums[i] + nums[len - 3] + nums[len - 2] + nums[len - 1] < target) { continue; }
for (int j = i + 1; j < len - 2; ++j) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) { break; } if (nums[i] + nums[j] + nums[len - 2] + nums[len - 1] < target) { continue; } int left = j + 1; int right = len - 1; while (left < right) { int sum = nums[i] + nums[j] + nums[left] + nums[right]; if (sum < target) { left++; } else if (sum > target) { right--; } else { vector<int> result = {nums[i], nums[j], nums[left], nums[right]}; results.emplace_back(result); while (left < right && nums[left] == nums[left + 1]) { left++; } left++; while (left < right && nums[right - 1] == nums[right]) { right--; } right--; } } } } return results; } };
int main() { vector<int> input; vector<vector<int>> results;
input = {1,0,-1,0,-2,2}; results = Solution().fourSum(input, 0); for (int i = 0; i < results.size(); ++i) { for (int j = 0; j < results[i].size(); ++j) { std::cout << results[i][j] << " "; } std::cout << std::endl; } }
|