Leetcode 3Sum, leetcode3sum
We assume that the three numbers of indexes are a, B, and c.
Duplicate production may occur in the following situations:
1. The first number leads to repetition, num [a] = num [A-1], followed by the same combination of B, c will lead to repeated answers
2. Repeat results from the second and third numbers only after an answer is found. Therefore, you only need to confirm that B ++, c -- is a different number.
vector<vector<int>> threeSum(vector<int> &num) { int b, c, n = num.size(); vector<vector<int>> result; sort(num.begin(), num.end()); for(int i = 0; i < n-2; i++){ if(i > 0 && num[i] == num[i-1]) continue; b = i+1; c = n-1; while(b < c){ if(num[i] + num[b] + num[c] < 0) b++; else if(num[i] + num[b] + num[c] > 0) c--; else { vector<int> tmp; tmp.push_back(num[i]); tmp.push_back(num[b]); tmp.push_back(num[c]); result.push_back(tmp); b++;c--; while(num[b] == num[b-1]) // avoid duplicates b++; while(num[c] == num[c+1]) c--; } } } return result; }