Topic meaning: Give a random ordinal group, in which look for all cases of three numbers and for 0, these conditions cannot be repeated, ascending order
Idea: The front 2sum, I use a map, natural that the problem map is more efficient than the double pointer, the problem needs to be sorted first, and then give three pointers, I, J, K
For the I pointer is traversed backwards, for a fixed I pointer, in fact, is the case of 2Sum, given a previous two pointers to traverse,
When the value is large, move the back of the pointer forward, the value is small, and move the front pointer backward.
The trouble is to go to the heavy, first of all I pointer to the weight, J and K only with a weight to be able to
PS: This is a very common method in arrays.
1 classSolution {2 Public:3vector<vector<int>> Threesum (vector<int>&nums) {4vector<vector<int>>ans;5vector<int> Temp (3);6 intSize=nums.size ();7 intj,k;8 sort (Nums.begin (), Nums.end ());9 for(intI=0; i<size-2;++i) {// Note This position can be written nums.size (), Just can't write Nums.size ()-2, what's the reason I haven't figured it out yet. Ten //while (i>0&&nums[i]==nums[i-1]) ++i; Pay attention to comparing two ways of writing One if(i>0&&nums[i]==nums[i-1])Continue; Aj=i+1; -k=size-1; - while(j<k) { the if(j>i+1&&nums[j]==nums[j-1]){ -++J; - Continue; - } + if(Nums[j]+nums[k]>-nums[i])--K; - Else if(Nums[j]+nums[k]<-nums[i]) + +J; + Else{ Atemp[0]=Nums[i]; attemp[1]=Nums[j]; -temp[2]=Nums[k]; - Ans.push_back (temp); -++J; ---K; - } in } - } to returnans; + } -};
Complexity: O (n2)
3Sum (look for the sum of three numbers for the set of the specified number of medium)