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

# Contains Duplicate II

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.

## 1. 暴力解法 O(n^2), 超时

```
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] == nums[j] and abs(i-j) <= k:
                    return True
        return False
```

## 2. Hashmap

```
 class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        charmap = {}
        for i in range(len(nums)):
            if nums[i] in charmap and abs(i-charmap[nums[i]]) <= k:
                return True
            else:
                charmap[nums[i]] = i
        return False
```
