---
title: "Contains Duplicate II"
author: "KickCode"
date: "2016-02-21T02:36:35Z"
tags: []
categories: ["编程语言"]
slug: "contains-duplicate-ii"
draft: false
lastmod: "2016-02-21T02:36:35Z"
id: 2277655
url: "https://kickcode.iteye.com/blog/2277655"
---

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* = nums and the difference between i and j is at most k.

给定一个数组判断数组中是否存在两个相同的数，它们之间的差最大为k。我们借助HashMap, key中存放数组的元素nums*，value中存放对应的下标i。如果遇到相同的key，就对比当前元素的下标i与key中value的值与k的大小，如果i - get(key) 小于等于k就说明存在，返回true。代码入下：

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

```