[LeetCode15]3Sum

来源:互联网 发布:知乎和百度有什么区别 编辑:程序博客网 时间:2024/06/01 08:18

Given an array S of n integers, are there elements abc 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)
分析
先排序,然后左右夹逼,复杂度 O(n2)。
这个方法可以推广到 k-sum,先排序,然后做 k − 2 次循环,在最内层循环左右夹逼,
时间复杂度是 O(max{n log n, nk−1})。

class Solution15{public:vector<vector<int>>threeSum(vector<int>& num){vector<vector<int>> result;if (num.size() < 3) return result;sort(num.begin(), num.end());const int target = 0;/*vector<int>::iterator iter;for (iter = num.begin(); iter != num.end(); iter++){cout << *iter << endl;}*/auto last = num.end();for (auto i = num.begin(); i < last - 2; ++i){auto j = i + 1;if (i>num.begin() && *i == *(i - 1)) continue;auto k = last - 1;while (j < k){if (*i + *j + *k < target){++j;while (*j == *(j - 1) && j < k)++j;}else if (*i + *j + *k>target){--k;while (*k == *(k + 1) && j < k)--k;}else{result.push_back({ *i, *j, *k });++j;--k;while (*j == *(j - 1) && *k == *(k + 1) && j < k)++j;}}}return result;}};int main15(){Solution15 solution;vector<int> vec = { -1, 0, 1, 2, -1, -4 };solution.threeSum(vec);getchar();return 0;}







0 0
原创粉丝点击