leetcode 220: Contains Duplicate III

Use set to find numbers with time complexity of O(n*logk). Learned this from http://www.cnblogs.com/easonliu/p/4544073.html.

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        set<int> window;
        int n=nums.size();
        for(int i=0;i<n;i++)
        {
            if(window.size()>k)
                window.erase(window.find(nums[i-k-1]));
            set<int>::iterator it;
            it=window.lower_bound(nums[i]-t);
            if(it!=window.end()&&abs(*it-nums[i])<=t)
                return true;
            window.insert(nums[i]);
        }
        return false;
    }
};
Use unordered map to implement the bucket sort can reduce the time complexity to O(n). The index of one bucket is calculated by idx=(nums[i]-INT_MIN)/(t+1). The reason I divide t+1 is to avoid the error when t is 0. Then I find out whether that bucket is empty. If not, return true. But if so, I also need to check the bucket idx-1 and bucket idx+1. If the numbers in that two buckets have differences with nums[i] less than or equal to t, return true. Then if all buckets contains more than k numbers, I need to erase the left most number.

This is learned from discuss: https://leetcode.com/discuss/38206/ac-o-n-solution-in-java-using-buckets-with-explanation.

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        if(k<1||t<0)
            return false;
        unordered_map<long long,long long> bucket;
        int n=nums.size();
        for(int i=0;i<n;i++)
        {
            long long idx=((long long)nums[i]-INT_MIN)/((long long)t+1);
            if(bucket.find(idx)!=bucket.end()||
                bucket.find(idx-1)!=bucket.end()&&(long long)nums[i]-bucket[idx-1]<=(long long)t||
                    bucket.find(idx+1)!=bucket.end()&&bucket[idx+1]-(long long)nums[i]<=(long long)t)
                        return true;
            bucket.insert(make_pair(idx,nums[i]));
            if(bucket.size()>k)
            {
                idx=((long long)nums[i-k]-INT_MIN)/((long long)t+1);
                bucket.erase(bucket.find(idx));
            }
        }
        return false;
    }
};


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