0
点赞
收藏
分享

微信扫一扫

<leetcode>219.存在重复元素II

林塬 2022-01-20 阅读 55

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int len = nums.size();
        map<int,int> dictionary;
        for(int i = 0; i < len; i++){
            int num = nums[i];
            if(dictionary.count(num) && i - dictionary[num] <= k){
                return true;
            }
            dictionary[num] = i;
        }
        return false;
    }
};
举报

相关推荐

0 条评论