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)
Problem: Find the array, all and three elements of 0.
Problem Solving Ideas:
I think of a solution, but threw it out of time, and then on the Internet to see the use of double pointer algorithm, after understanding, the problem solved.
The first step is to sort the array.
Step Two,
Analysis 1: For the element S[i], the final answer can be divided into two types, including s[i], and does not contain s[i]. When the case with S[i] is found, the following can not be considered s[i].
For s[i], L = i+1, r = len-1. If s[i] + s[l] + s[r] = = 0, then a solution to the original problem.
- When S[i] + s[l] >-s[r], the r--
- When S[i] + S[l] <-s[r], the l++
- When S[i] + s[i] =-s[r], the expression is a solution to the original problem, then l++, r--;
The third step, performance optimization. Also according to analysis 1, if s[i] = = S[i+1], you can skip.
vector<vector<int>> Threesum (vector<int>&nums) {Vector<vector<int>>Res; Std::sort (Nums.begin (), Nums.end ()); Map<string, vector<int>>Key_res; for(inti =0; I < (int) Nums.size (); i++) { //Star Pruning optimization if(I >=1) { while(Nums[i] = = nums[i-1]) {i++; Continue; } } //End Pruning Optimization intL = i+1; intR = (int) Nums.size ()-1; while(L <r) {if(Nums[l] + nums[r] >-Nums[i]) {R--; Continue; } Else if(Nums[l] + Nums[r] <-Nums[i]) {L++; }Else{ stringK = to_string (Nums[i]) +","+ to_string (Nums[l]) +","+to_string (Nums[r]); Vector<int> tmp ={nums[i], nums[l], Nums[r]}; KEY_RES[K]=tmp; L++; R--; }}} Map<string, vector<int>>:: Iterator m_iter; for(M_iter = Key_res.begin (); M_iter! = Key_res.end (); m_iter++) {res.push_back (M_iter-second); } returnRes;}
[Leetcode] 3Sum problem Solving ideas