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:
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
此题最naiev的做法是3层循环遍历所有可能的情况。此时时间复杂度是O(n^3);
较好的做法是对num数组排序。然后外层设置1层循环,内层即可看作求两个数的和为给定值的问题。(注意:此时的数组是有序的呦!较好的用好这个序关系就可以在O(n)的时间内解决2Sum问题。)。该方法最终的时间复杂度是O(n^2).
vector<vector<int> > threeSum(vector<int> &num) { //C++ vector<vector<int> > res; if (num.size() <= 2) return res; sort(num.begin(), num.end()); int twoSum; for (int i = 0; i < num.size() - 2;) { int l = i + 1, r = num.size() - 1; twoSum = 0 - num[i]; while (l < r) { if (num[l] + num[r] < twoSum) l++; else if (num[l] + num[r] == twoSum) { vector<int> three(3); three[0] = num[i]; three[1] = num[l]; three[2] = num[r]; res.push_back(three); do { l++; }while (l < r && num[l - 1] == num[l]); do { r--; }while (l < r && num[r + 1] == num[r]); } else r--; } do{ i++; }while (i < num.size() - 1 && num[i - 1] == num[i]); } sort(res.begin(),res.end()); return res; }
原文地址:http://blog.csdn.net/chenlei0630/article/details/41151955