LeetCode Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

要是面试,那么我已经跪了

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        if (t < 0 || k <1) {
            return false;
        }
        long bucket_size = (long)t + 1;
        long len = nums.size();
        unordered_map<long, long> buckets;
        for (long i=0; i<len; i++) {
            long val = nums[i] - (long)INT_MIN;
            long bucket = val / bucket_size;
            // check duplicates in buckets[bucket-1], buckets[bucket], buckets[bucket+1]
            if (buckets.count(bucket) > 0 
                || buckets.count(bucket-1) > 0 && val - buckets[bucket - 1] <= t
                || buckets.count(bucket+1) > 0 && buckets[bucket + 1] - val <= t) {
                return true;        
            }
            // maintain buckets entries in a k size window (the index constrains)
            if (buckets.size() >= k) {
                int bucket2del = (nums[i - k] - (long)INT_MIN) / bucket_size;
                buckets.erase(bucket2del);
            }
            buckets[bucket] = val;
        }
        return false;
    }
};

 用set不靠谱啊,这个提示binary search tree难道不是这么用,直接TLE了:

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        if (t < 0 || k <1) {
            return false;
        }
        int len = nums.size();
        set<long> win;
        
        for (int i=0; i<len; i++) {
            long val = nums[i];
            auto lo = lower_bound(win.begin(), win.end(), val - t);
            if (lo != win.end()) {
                if (abs(*lo - val) <= t) {
                    return true;
                } else {
                    // not found
                }
            }
            // sliding window
            if (i >= k) {
                win.erase(nums[i - k]);
            }
            win.insert(val);
        }
        
        return false;
    }
};

 

posted @ 2015-06-07 11:31  卖程序的小歪  阅读(297)  评论(0编辑  收藏  举报