3Sum

来源:互联网 发布:淘宝卖家都用什么软件 编辑:程序博客网 时间:2024/06/05 20:53

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)
class Solution {public:    vector<vector<int> > threeSum(vector<int> &num){vector<vector<int> > res;sort(num.begin(), num.end());int size = num.size();for (int i = 0; i <= size - 3; i++){if (i > 0 && num[i] == num [i - 1])continue;int s = i + 1, e = size - 1;while(s < e){if (num[s] + num[e] == -num[i]){vector<int> tmp;tmp.push_back(num[i]);tmp.push_back(num[s++]);tmp.push_back(num[e--]);res.push_back(tmp);while(num[s] == num[s - 1])s++;while(num[e] == num[e + 1])e--;}else if (num[s] + num[e] < -num[i])s++;elsee--;}}return res;    }};






0 0