https://leetcode.com/problems/3sum/
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)
Method One:
Two-layer loop + binary lookup, complexity O (n^2 logn). It's too slow.
1 classSolution {2 Public:3vector<vector<int>> Threesum (vector<int>&nums) {4 Set<vector<int>>Res;5vector<vector<int>>output;6vector<int>Sol;7Sort (Nums.begin (), Nums.end ());//Sort First8 inti,j,k,t,x,n=nums.size ();9 for(i=0; i<n;i++){Ten for(j=i+1; j<n-1; j + +){ Onet=nums[i]+Nums[j]; AX=findsol (-t,nums,j+1, N-1); - if(x!=-1){ - sol.clear (); the Sol.push_back (Nums[i]); - Sol.push_back (Nums[j]); - Sol.push_back (nums[x]); - Res.insert (sol); + } - } + } A Set<vector<int>>:: iterator iter; at for(Iter=res.begin (); Iter!=res.end (); iter++){ -Output.push_back (*iter); - } - returnoutput; - } - intFindsol (inttarget,vector<int> Nums,intBeginintend) { in if(nums[begin]==target) - returnbegin; to if(nums[end]==target) + returnend; - if(nums[begin]>target| | nums[end]<target) the return-1; * intmid; $ while(begin<=end) {Panax NotoginsengMid= (begin+end)/2; - if(nums[mid]==target) the returnmid; + Else if(nums[mid]>target) { Aend=mid-1; the } + Else -Begin=mid+1; $ } $ return-1; - } -};
Method Two: One layer of the loop plus the sum two (https://leetcode.com/problems/two-sum/), O (n^2).
1 classSolution {2 Public:3vector<vector<int>> Threesum (vector<int>&nums) {4 sort (Nums.begin (), Nums.end ());5vector<vector<int>>Res;6 inti,t,a,b,k,n=nums.size ();7 for(i=0; i<n-2; i++){8t=-Nums[i];9a=i+1;Tenb=n-1; One while(a<b) { Ak=nums[a]+Nums[b]; - if(k<t) { -a++; the } - Else if(k>t) { -b--; - } + Else{ -vector<int> Sol (3,0); +sol[0]=Nums[i]; Asol[1]=Nums[a]; atsol[2]=Nums[b]; - Res.push_back (sol); - while(A < b && nums[a] = = sol[1]) -a++; - while(A < b && nums[b] = = sol[2]) -b--; in } - } to while(i +1< Nums.size () && nums[i +1] ==Nums[i]) +i++; - } the * //Deduplicate, but it's so slow! $ //sort (Res.begin (), Res.end ()); Panax Notoginseng //res.erase (Unique (Res.begin (), Res.end ()), Res.end ()); - returnRes; the } +};
Leetcode (15)--3sum