LeetCode 15 3Sum

    xiaoxiao2021-03-26  4

    题意:

    求不重复的使得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; } };

    转载请注明原文地址: https://ju.6miu.com/read-500379.html

    最新回复(0)