论坛首页 编程语言技术论坛

[Leetcode] 3Sum

浏览 1113 次
锁定老帖子 主题:[Leetcode] 3Sum
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-08-13  

3Sum
Jan 18 '128685 / 33750

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) {
        sort(num.begin(), num.end());
        vector<vector<int> > res;
        int len = num.size();
        for (int i = 0; i < len - 2; i++) {
            if (i > 0 && num[i] == num[i-1]) continue;
            int a = i+1, b = len -1; 
            int t = -num[i];
            while (a < b) {
                if (num[a] + num[b] == t) {
                    int tmp[3] = {-t, num[a], num[b]};
                    vector<int> tmp2(tmp, tmp+3);
                    res.push_back(std::move(tmp2));
                    while (a < b && num[a] == num[a+1]) a++;
                    a++;
                    while (a < b && num[b] == num[b-1]) b--;
                    b--;
                }
                else if (num[a] + num[b] > t) {
                    b--;
                } else  a++;
            }
        }
        return res;
    }
};

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics