leetcode 219: Contains Duplicate II

Use the unordered map to save the number and its index. And the rest is easy.

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int> mp;
        int n=nums.size();
        for(int i=0;i<n;i++)
        {
            if(mp.find(nums[i])!=mp.end())
                if(i-mp[nums[i]]<=k)
                    return true;
            mp[nums[i]]=i;
        }
        return false;
    }
};


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