Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Maintain a hashset with size of (K + 1)

class Solution 
{
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) 
    {
        unordered_set<int> hs;
        for (int i = 0; i < nums.size(); i ++)
        { 
            if (hs.size() > k)
                hs.erase(nums[i - k - 1]);
            if (hs.find(nums[i]) != hs.end())
                return true;
                
            hs.insert(nums[i]);
        }
        return false;
    }
};
posted on 2015-05-30 01:36  Tonix  阅读(160)  评论(0)    收藏  举报