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:
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)
分析:
借助STL的去重方法unique()实现,先排序,然后左右夹逼,时间复杂度 O(n^3) ,空间复杂度 O(1)
简单介绍——unique方法
在STL中unique函数是一个去重函数, unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。
例子:
{
sort(words.begin(), words.end());
vector<string>::iterator end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
}
//方法一:先排序,然后左右夹逼,时间复杂度 O(n^3) ,空间复杂度 O(1) class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int> > result; if(nums.size() < 4) return result; sort(nums.begin(), nums.end()); for(vector<int>::iterator i = nums.begin(); i < nums.end() - 3; i++) { if(i > nums.begin() && *i == *(i-1)) continue; for(vector<int>::iterator j = i+1; j < nums.end() - 2; j++) { if(j > i+1 && *j == *(j-1)) continue; vector<int>::iterator k = j + 1; vector<int>::iterator l = nums.end() - 1; while(k < l) { if(*i + *j + *k + *l < target) k++; else if(*i + *j + *k + *l> target) l--; else { result.push_back({*i, *j, *k, *l}); k++; l--; } } } } //sort(result.begin(), result.end()); vector<vector<int> >::iterator unique_end = unique(result.begin(), result.end()); result.erase(unique_end, result.end()); //result.erase(unique(result.begin(), result.end()), result.end()); return result; } };
//还有另外三种方法,待研究通后再添加