Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
For example, given array S = {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)
分析:和3Sum的做法类似,将数组排序后,固定第一、二个数,然后从两边夹逼第三、四个数。注意检查重复数字出现的情况。
Solution1: 运行时间129ms。
1 class Solution { 2 public: 3 vector<vector<int> > fourSum(vector<int>& nums, int target) { 4 vector<vector<int> >result; 5 if(nums.size() < 4) return result; 6 sort(nums.begin(), nums.end()); 7 8 for(int a = 0; a < nums.size() - 3; a++){ 9 if(a != 0 && nums[a] == nums[a-1]) continue; 10 for(int b = a + 1; b < nums.size() - 2; b++){ 11 if(b != a + 1 && nums[b] == nums[b-1]) continue; 12 int c = b + 1, d = nums.size() - 1; 13 14 while(c < d){ 15 if(nums[a] + nums[b] + nums[c] + nums[d] > target) d--; 16 else if(nums[a] + nums[b] + nums[c] + nums[d] < target) c++; 17 else{ 18 if(c != b + 1 && nums[c] == nums[c-1]) c++; 19 else if(d != nums.size() - 1 && nums[d] == nums[d+1]) d--; 20 else{ 21 result.push_back({nums[a], nums[b], nums[c], nums[d]}); 22 c++; 23 d--; 24 } 25 } 26 } 27 } 28 } 29 sort(result.begin(), result.end()); 30 return result; 31 } 32 };
Solution2:用map进行存储与判断,耗时更多。160ms。不推荐。
1 class Solution { 2 public: 3 vector<vector<int> > fourSum(vector<int>& nums, int target) { 4 vector<vector<int> >result; 5 if(nums.size() < 4) return result; 6 sort(nums.begin(), nums.end()); 7 8 for(int a = 0; a < nums.size() - 3; a++){ 9 if(a != 0 && nums[a] == nums[a-1]) continue; 10 for(int b = a + 1; b < nums.size() - 2; b++){ 11 if(b != a + 1 && nums[b] == nums[b-1]) continue; 12 int c = b + 1, d = nums.size() - 1; 13 map<int, int> hmap; 14 15 while(c < d){ 16 if(nums[a] + nums[b] + nums[c] + nums[d] > target) d--; 17 else if(nums[a] + nums[b] + nums[c] + nums[d] < target) c++; 18 else{ 19 if(hmap.find(nums[c]) == hmap.end()){ 20 hmap[nums[c]] = nums[d]; 21 result.push_back({nums[a], nums[b], nums[c], nums[d]}); 22 } 23 c++; 24 d--; 25 } 26 } 27 } 28 } 29 sort(result.begin(), result.end()); 30 return result; 31 } 32 };