LeetCode 15 3Sum

来源:互联网 发布:淘宝店铺四个钻石 编辑:程序博客网 时间:2024/06/14 07:53

题意:

求不重复的使得x + y + z = 0的(x, y, z)组合。


思路:

为了防止重复可以按x <= y <= z来枚举,z可以用map来查找。

我的代码好慢…不知道是不是用了long long的缘故…求快速的代码??


代码:

//// Created by house on 1/9/17.//class Solution {public:    vector <vector<int>> threeSum(vector<int> &nums) {        vector <vector<int>> ans;        map<long long, int> cnt;        for (int x : nums) {            ++cnt[x];        }        for (map<long long, int>::iterator it1 = cnt.begin(); it1 != cnt.end(); ++it1) {            int x = it1->first;            --cnt[x];            for (auto it2 = it1; it2 != cnt.end(); ++it2) {                if (it2->second) {                    int y = it2->first;                    --cnt[y];                    long long sum = (long long) x + y;                    if (-sum >= y && cnt.count(-sum) && cnt[-sum] > 0) {                        vector<int> tmp{x, y, -sum};                        ans.push_back(tmp);                    }                    ++cnt[y];                }            }            ++cnt[x];        }        return ans;    }};


0 0