[leetcode刷题系列]3Sum

循环枚举前两个, 然后二分查找第三个,嗯, 用hash_map判重


class vector_int_hash{
        const static int P = 10007;
        const static int MOD = 1e9 + 7;
    public:
        size_t operator() (const vector<int> &v)const{
            long long now = 0;
            for(int i = 0; i < v.size(); ++ i)
                now = (now * P + v[i] ) % MOD;
            return now;
        }
};

class vector_int_comp{
    public:
        int operator() (const vector<int> &a, const vector<int> & b)const{
            if(a.size() != b.size())
                return 0;
            for(int i = 0; i < a.size(); ++ i)
                if(a[i] != b[i])
                    return 0;
            return 1;
        }
};
class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(num.begin(), num.end());
        vector<vector<int> > ans;
        //map<vector<int>, bool> hash;
        unordered_map<vector<int>, bool,vector_int_hash,vector_int_comp> hash;
        for(int i = 0; i < num.size() && num[i] <= 0; ++ i)
            for(int j = i + 1; j < num.size(); ++ j){
                int target = 0 - (num[i] + num[j]);
                int low = j + 1, high = num.size() - 1,mid;
                while(low <= high)
                    if(num[mid = low + high >> 1] >= target) high = mid - 1;else low = mid + 1;
                if(low < num.size() && num[low] == target){
                    vector<int> v;
                    v.push_back(num[i]);
                    v.push_back(num[j]);
                    v.push_back(target);
                    if(hash.find(v) != hash.end())
                        continue;
                    hash[v] = true;
                    ans.push_back(v);
                }
            }
        return ans;
    }
};


猜你喜欢

转载自blog.csdn.net/sigh1988/article/details/10008219