#Leetcode# 18. 4Sum
https://leetcode.com/problems/4sum/
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
代码:
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); set<vector<int>> ans; int n = nums.size(); for(int i = 0; i < n - 3; i ++) { for(int j = i + 1; j < n - 2; j ++) { int num = nums[i] + nums[j]; int find = target - num; int l = j + 1, r = n - 1; while(l < r) { if(nums[l] + nums[r] == find) { ans.insert({nums[i], nums[j], nums[l], nums[r]}); while(l < r && nums[l] == nums[l + 1]) l ++; while(l < r && nums[r] == nums[r - 1]) r --; l ++; r --; } else if(nums[l] + nums[r] > find) r --; else l ++; } } } return vector<vector<int>>(ans.begin(), ans.end()); } };
这个和之前的 3Sum 还有 3Sum Closest 一样的 时间复杂度是 $O(n ^ 3)$ 不知道还有没有更简单的方法
emmmm 这个颜色好像芋泥 嘻嘻