题目:
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)
解题思路:
先对num排序,然后从两头枚举两个数,O(n^2),后两个数在前两个数之间的两端开始,和小了左边的往右,和大了右边的往左调整,O(n),总共O(n^3)。
代码:
1 class Solution { 2 public: 3 vector<vector<int> > fourSum(vector<int> &num, int target) { 4 sort(num.begin(), num.end()); 5 vector<vector<int>> ans; 6 7 for (int left = 0; left < num.size(); ) { 8 for (int right = num.size()-1; right > left+2; ) { 9 int sum_of_two = num[left] + num[right]; 10 11 int ml = left + 1, mr = right - 1; 12 while (ml < mr) { 13 if (sum_of_two + num[ml] + num[mr] == target) { 14 vector<int> cur_ans = {num[left], num[ml], num[mr], num[right]}; 15 ans.push_back(cur_ans); 16 ml++; 17 mr--; 18 } else if (sum_of_two + num[ml] + num[mr] < target) { 19 ml ++; 20 } else { 21 mr --; 22 } 23 //去重 24 while (ml < mr && (ml != left + 1 && num[ml] == num[ml-1])) ml ++; 25 while (ml < mr && (mr != right - 1 && num[mr] == num[mr+1])) mr--; 26 } 27 for(right --; right > left + 2 && num[right] == num[right + 1]; right --); 28 } 29 for(left ++; left < num.size() - 3 && num[left] == num[left - 1]; left ++); 30 } 31 return ans; 32 } 33 };