3Sum
Given an array S of n integers, is 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 is 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)
Ideas:
Similar to the 3Sum closet, only this time it is a collection. And if you find the sum of three numbers equals 0, pay attention to the second number or the third number to change, or you will fall into the loop of death.
Exercises
classSolution { Public: Vector<vector<int> > Threesum (vector<int> &num) {Vector<vector<int> >Res; Vector<int>tmp; Sort (Num.begin (), Num.end ()); for(intI=0; I<num.size (); i++) { while(i>0&& num[i]==num[i-1]) I++; intL = i+1; intR = num.size ()-1; while(l<r) { while(l>i+1&& num[l]==num[l-1]) L++; while(R<num.size ()-1&& num[r]==num[r+1]) R--; if(l<r) {intsum = num[i]+num[l]+Num[r]; if(sum>0) R--; Else if(sum<0) L++; Else{tmp.clear (); Tmp.push_back (Num[i]); Tmp.push_back (Num[l]); Tmp.push_back (Num[r]); Res.push_back (TMP); L++; } } } } returnRes; }};View Code
[Leetcode] 3Sum