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)
先升序排序,然后用第一重for循環確定第一個數字。
然后在第二重循環里,第二、第三個數字分別從兩端往中間掃。
如果三個數的sum等於0,得到一組解。
如果三個數的sum小於0,說明需要增大,所以第二個數往右移。
如果三個數的sum大於0,說明需要減小,所以第三個數往左移。
時間復雜度:O(n2)
注意:
1、排序之后天然滿足non-descending order的要求
2、為了避免重復,在沒有空間要求情況下可以用map,但是也可以跳過重復元素來做。
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > ret; int size = num.size(); sort(num.begin(), num.end()); for(int i = 0; i < size; i ++) { //skip same i while(i > 0 && i < size && num[i] == num[i-1]) i ++; int j = i + 1; int k = size - 1; while(j < k) { int sum = num[i] + num[j] + num[k]; if(sum == 0) { vector<int> cur(3); cur[0] = num[i]; cur[1] = num[j]; cur[2] = num[k]; ret.push_back(cur); j ++; k --; //skip same j while(j < k && num[j] == num[j-1]) j ++; //skip same k while(k > j && num[k] == num[k+1]) k --; } else if(sum < 0) { j ++; //skip same j while(j < k && num[j] == num[j-1]) j ++; } else { k --; //skip same k while(k > j && num[k] == num[k+1]) k --; } } } return ret; } };