Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
这道题可以用求两个数的和相同的解法来求解。需要注意的是对重复元素的处理,如果不加上这个减枝处理,在leetcode中会显示超时。
首先对数组进行排序,时间复杂度是O(Nlog(N))。
然后定义三个指针,第一个指针从头遍历到尾,第二个指针和第三个指针和求两个数的和时的那两个指针一样从两端开始遍历,左端由第一个指针来确定。这样时间复杂度是O(N^2)。总的时间复杂度是O(N^2)。一定要加上对重复元素的减枝处理。
runtime:68ms
class Solution {
public:
vector
> threeSum(vector
& nums) { int length=nums.size(); vector
> result; if(length<3) return result; sort(nums.begin(),nums.end()); auto iter1=nums.begin(); for(;iter1!=nums.end()-2;iter1++) { auto iter2=iter1+1; auto iter3=nums.end()-1; while(iter2
tmp; tmp.push_back(*iter1); tmp.push_back(*iter2); tmp.push_back(*iter3); result.push_back(tmp); while(*iter2==*(iter2+1)&&(iter2+1)
?