# 219.Contains Duplicate II

**219.Contains Duplicate II**

难度:Easy

> 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 absolute difference between i and j is at most k.

```
Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false
```

新建一个map保存相同元素的索引值，然后比较相同元素索引值中相邻两个索引是否有满足条件的。

```
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, vector<int >> cnt;
        for(int i=0;i<nums.size();i++)
            cnt[nums[i]].push_back(i);
        for(auto c:cnt)
            if(c.second.size()>1)
            {
                for(int i=1;i<c.second.size();i++)
                    if(c.second[i]-c.second[i-1]<=k)
                        return true;
                    }
        return false;
    }
};
```

> 执行用时 :56 ms, 在所有 C++ 提交中击败了50.75%的用户\
> 内存消耗 :22 MB, 在所有 C++ 提交中击败了5.03%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/219.contains_duplicate_ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
