Topic
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)
Analysis
The sequence of three of the sum of 0 in a given integer sequence is calculated!
I used a violent solution, three-layer loop, but Status:time Limit exceeded~~~
We haven't figured out a more efficient code.
Time Limit exceeded code
classSolution { Public: vector<vector<int>>Threesum ( vector<int>& Nums) { vector<vector<int>>vvintSize = Nums.size ();if(Size <3)returnvv for(inti =0; i < size; i++) { for(intj = i +1; J < size; J + +) { for(intK = j +1; K < size; k++) {if(Nums[i] + nums[j] + nums[k] = =0) {intarr[3] = {Nums[i], nums[j], nums[k]};//Sort the elements in arr from small to largeSort (arr); vector<int>v = {arr, arr +3};if(!find (vv, v)) Vv.push_back (v); }Else{Continue; } }//for}//for}//for returnvv }BOOLFind vector<vector<int>>&VV, vector<int>&V) { vector<vector<int>>:: Iterator iter; for(iter = Vv.begin (); ITER! = Vv.end (); iter++) {if((*iter) [0] = = v[0] && (*iter) [1] = = v[1] && (*iter) [2] = = v[2]) {return true; } }return false; }voidSortint*a) { for(inti =0; I <3; i++) { for(intj =0; J <3I1; J + +) {if(A[j] > a[j +1]) {intt = a[j]; A[J] = a[j +1]; A[j +1] = t; } } } }};
AC Code
Waiting to be added ~ ~
Leetcode (3Sum)