LeetCode --- 15. 3Sum
Link: 3Sum
Given an array S of n integers, are 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 be 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)
The requirement for this question is to find three numbers in the given positive integer array so that the sum of them is equal to 0. The three numbers must be arranged in non-descending order and do not contain duplicates.
The idea of this question is similar to the previous Two Sum. The simple method is to perform brute force search, sort the question first, and then traverse the array in three layers in a loop. the time complexity is O (n3 ). During optimization, You can first fix a number, and then use two pointers, l and r, to search between the two sides of the number. When the sum of these three numbers is equal to 0, record it, when the sum is greater than 0, r shifts left, and when the sum is less than 0, l shifts right until l and r meet each other. This is actually adding a layer 1 loop in the outer layer of Two Sum, so the time complexity is the sorting O (nlogn) plus O (n2), that is, O (n2 ).
Because the three numbers need to be discharged in a non-decreasing sequence, sorting can meet this requirement. It is required that the duplicate element is not included. Therefore, when selecting the first number and the next two pointers, you must skip the duplicate element.
Time Complexity: O (n2)
Space complexity: O (1)
1 class Solution 2 {3 public: 4 vector
> ThreeSum (vector
& Num) 5 {6 vector
> V; 7 8 if (num. size () = 0) 9 return v; 10 11 sort (num. begin (), num. end (); 12 13 for (int I = 0; I <num. size ()-2 & num [I] <= 0; ++ I) 14 {15 if (I> 0 & num [I] = num [I-1]) // skip repeated element 16 continue; 17 18 int l = I + 1, r = num. size ()-1; 19 while (l <r) 20 {21 if (num [l] + num [r] = 0-num [I]) 22 {23 v. push_back ({num [I], num [l], num [r]}); 24 25 + + l, -- r; 26 while (l <r & num [l] = num [l-1]) // skip repeat element 27 + l; 28 while (l <r & num [r] = num [r + 1]) // skip repeat element 29 -- r; 30} 31 else if (num [l] + num [r]> 0-num [I]) 32 -- r; 33 else34 + + l; 35} 36} 37 38 return v; 39} 40 };