# Contains Duplicate II

<https://leetcode.com/problems/contains-duplicate-ii/description/>

> Given an array of integers and an integerk, find out whether there are two distinct indicesiandjin the array such that**nums\[i] = nums\[j]**&#x61;nd the**absolute**difference betweeniandjis at mostk.

## Thoughts

问两个坑是否装同一个数，且坑的indexの差小于k. 遍历，如果当前元素在map中则计算它和当前index的差。map更新为当前的i, 因为要求找最近的，当后面还出现该元素时和i的diff肯定比和i之前的diff小。

## Code

```
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                if (i - map.get(nums[i]) <= k) {
                    return true;
                }
            }
            map.put(nums[i], i);
        }

        return false;
    }
}
```

## Analysis

时间空间都是O(n).


---

# 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://hao-fu-1.gitbook.io/oj/hash/jian-guo/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.
