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.
Ideas:
The minimum value is looped from beginning to end, and the median and maximum are shrunk.
I write in the last to repeat, always timed out. Later looked at the people's answer, found that each time on the smallest, middle, maximum weight . It'll be AC.
#include <iostream>#include<vector>#include<algorithm>#include<queue>#include<stack>using namespacestd;classSolution { Public: Vector<vector<int> > Threesum (vector<int> &num) {Vector<vector<int> >ans; if(Num.size () <3) { returnans; } intsmall =0; intBig = Num.size ()-1; intMID =0; intsum =0; Sort (Num.begin (), Num.end ()); for(small =0; Small < Num.size ()-2;/*small++*/)//minimum number of loops in the middle and the maximum number of sides contraction{mid= Small +1; Big= Num.size ()-1; while(Mid <big) {Sum= Num[small] + Num[mid] +Num[big]; if(Sum >0) {Big--; } Else if(Sum <0) {Mid++; } Else{vector<int>v; V.push_back (Num[small]); V.push_back (Num[mid]); V.push_back (Num[big]); Ans.push_back (v); Do{mid++;} while(Mid < big && Num[mid-1] = = Num[mid]);//Attention!! Do{big--;} while(Mid < big && Num[big +1] = = Num[big]);//Attention!! } } Do{small++;} while(Small < Num.size ()-1&& Num[small-1] = = Num[small]);//Attention!! } returnans; }};intMain () {solution S; Vector<int>num; Num.push_back (-4); Num.push_back (-1); Num.push_back (-1); Num.push_back (-1); Num.push_back (-1); Num.push_back (0); Num.push_back (0); Num.push_back (0); Num.push_back (1); Num.push_back (2); Vector<vector<int>> ans =s.threesum (num); return 0;}
"Leetcode" 3Sum (medium)