地址 https://leetcode-cn.com/problems/4sum/
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?
找出所有满足条件且不重复的四元组。 注意: 答案中不可以包含重复的四元组。 示例: 给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
解答
相当于 LeetCode 015. 三数之和 双指针 外面再套一层
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums,int target) { vector<vector<int>> ans; sort(nums.begin(), nums.end()); for(int k = 0; k < nums.size();k++){ if (k != 0 && nums[k] == nums[k - 1]) continue; target -= nums[k]; for (int i = k+1; i < nums.size(); i++) { if (i-1 != k && nums[i] == nums[i - 1]) continue; target -= (nums[i]); int l = i + 1; int r = nums.size() - 1; while (l < r) { if (nums[l] + nums[r] == target) { vector<int> v{ nums[k], nums[i],nums[l],nums[r] }; ans.push_back(v); do { l++; } while (l < r&& nums[l] == nums[l - 1]); do { r--; } while (r > l && nums[r] == nums[r + 1]); } else if (nums[l] + nums[r] > target) { do { r--; } while (r > l && nums[r] == nums[r + 1]); } else if (nums[l] + nums[r] < target) { do { l++; } while (l < r&& nums[l] == nums[l - 1]); } } target += (nums[i]); }//for (int i = 0; i < nums.size(); i++) target += nums[k]; } return ans; } };
20210311
class Solution { public: vector<vector<int>> ans; vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int prevI = 1000000010; for (int i = 0; i < nums.size(); i++) { if (prevI == nums[i]) continue; int prevJ = 1000000010; for (int j = i + 1; j < nums.size(); j++) { if (prevJ == nums[j]) continue; int sum = nums[i] + nums[j]; int l = j + 1; int r = nums.size() - 1; while (l < r) { int total = sum + nums[l] + nums[r]; if (total == target) { ans.push_back(vector<int>{nums[i],nums[j],nums[l],nums[r]}); l++; while (l < r && nums[l] == nums[l - 1]) l++; } else if (total < target) { l++; while (l < r && nums[l] == nums[l - 1]) l++; } else if (total > target) { r--; while (l < r && nums[r] == nums[r + 1]) r--; } } prevJ = nums[j]; } prevI = nums[i]; } return ans; } };