[Array]Contains Duplicate II

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

利用unordered_set速度会比set速度快很多。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
       if(k==0)
        return false;
       unordered_set<int> st;
       for(int i=0;i<nums.size();i++){
           if(i>k)
             st.erase(nums[i-k-1]);
           if(st.find(nums[i])!=st.end()){
               return true;
           }
           st.insert(nums[i]);
       }
       return false;
    }
};
posted @ 2016-07-07 13:05  U_F_O  阅读(88)  评论(0编辑  收藏  举报