LeetCode 3Sum

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > res;
        int len = num.size();
        sort(num.begin(), num.end());
        vector<int> tmp(3, 0);
        for (int i=0; i<len; i++) {
            tmp[0] = num[i];
            if (i != 0 && num[i] == num[i-1]) continue; // skip dup
            int rs = 0 - num[i];
            int p = i + 1, q = len - 1;
            while (p<q) {
                if (p != i+1 && num[p] == num[p-1]) {
                    p++;
                    continue;   // skip dup
                }
                if (q != len-1 && num[q] == num[q+1]) {
                    q--;
                    continue;   // skip dup
                }
                int s = num[p] + num[q];
                if (s < rs) {
                    p++;
                } else if (s > rs) {
                    q--;
                } else {
                    tmp[1] = num[p];
                    tmp[2] = num[q];
                    res.push_back(tmp);
                    p++, q--;
                }
            }
        }
        return res;
    }
};

先暴力一下吧

第二轮:

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();
        if (len < 3) {
            return res;
        }
        for (int i=len-1; i>=2; i--) {
            if (i<len-1 && num[i] == num[i+1]) continue;
            int target = -num[i];
            int p = 0;
            int q = i-1;
            while (p < q) {
                int t = num[p] + num[q];
                if (t < target) {
                    p++;
                } else if (t > target) {
                    q--;
                } else {
                    if (!res.empty() 
                        && res.back()[0] == num[p]
                        && res.back()[1] == num[q]
                        && res.back()[2] == num[i]) {
                            
                    } else {
                        res.push_back(vector<int> ({num[p], num[q], num[i]}));
                    }
                    p++;
                }
            }
        }
        return res;
    }
};

 

posted @ 2014-04-16 19:49  卖程序的小歪  阅读(131)  评论(0编辑  收藏  举报