3sum
Q:
Given an array Sof nintegers, are there elements a, b, cin Ssuch 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)
排序之后,遍历数组每一个元素作为第一个元素,剩下两个元素分别去头和尾向中间滑动。
注意如果一个元素已经被选定为第一个元素,和它相同的值以后都不要再选定为第一个元素了。
A:
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > res; if (num.size() < 3) { return res; } sort(num.begin(), num.end()); res = threeSumInternal(num, 0); return res; } private: vector<vector<int> > threeSumInternal(const vector<int> &num, int sum) { vector<vector<int> > res; int len = num.size(); for (int i = 0; i < len - 2; ++i) { while (i > 0 && i < len && num[i] == num[i - 1]) { ++i; } if (i > len - 2) { break; } int begin = i + 1; int end = len - 1; while (begin < end) { if (num[i] + num[begin] + num[end] == sum) { vector<int> part_res; part_res.push_back(num[i]); part_res.push_back(num[begin]); part_res.push_back(num[end]); res.push_back(part_res); while (begin + 1 < len && num[begin + 1] == num[begin]) { ++begin; } while (end - 1 > 0 && num[end] == num[end - 1]) { --end; } ++begin; --end; } else if (num[i] + num[begin] + num[end] < sum) { ++begin; } else { --end; } } } return res; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号