> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/219.contains_duplicate_ii.md).

# 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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
