3Sum

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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > result;
        set<vector<int> > record;
        if (num.size() < 3) {
            return result;
        }
        sort(num.begin(), num.end());
        vector<int> got;
        int sum = 0;
        for (int i = 0; i < num.size() - 2; ++i) {
            int low = i + 1;
            int high = num.size() - 1;
            while (low < high) {
                sum = num[i] + num[low] + num[high];
                if (sum == 0) {
                    got.push_back(num[i]);
                    got.push_back(num[low]);
                    got.push_back(num[high]);
                    if (record.find(got) == record.end()) {
                        record.insert(got);
                        result.push_back(got);
                    }
                    got.clear();
                    --high;
                } else if (sum > 0) {
                    --high;
                } else {
                    ++low;
                }
            }
        }
        return result;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章