This was an extension of the 2Sum problem. The idea was pretty simple (even no need to use hash). Sort the array and then starting from the first element, set of pointers left and right: one after the Current element and the other at the end of the tail. If all the three elements sum to 0, then they is an answer. Add them to the result. Then your need to being careful to skip the duplicates! If you pay enough attention to the details, this problem have a fairly straightforward implementation without too many tric Ks.
The final code is as follows.
1vector<vector<int>> Threesum (vector<int>&nums) {2vector<vector<int> >Res;3 if(Nums.size () <=2)returnRes;4 sort (Nums.begin (), Nums.end ());5 intL =0, r = nums.size ()-1;6 for(inti =0; I < (int) Nums.size ()-2;) {7 intL = i +1, r = nums.size ()-1;8 while(L <r) {9 if(Nums[i] + nums[l] + nums[r] = =0) {Tenvector<int> Ans (3); Oneans[0] =Nums[i]; Aans[1] =Nums[l]; -ans[2] =Nums[r]; - res.push_back (ans); the while(L < r && Nums[l] = = ans[0]) l++; - while(R > L && nums[r] = = ans[2]) r--; - } - Else if(Nums[i] + nums[l] + Nums[r] >0) r--; + Elsel++; - } +i++; A while(I < (int) nums.size () && nums[i-1] = = Nums[i]) i++; at } - returnRes; -}
[Leetcode] 3Sum