219. Contains Duplicate II

来源:互联网 发布:复旦大学大数据试验场 编辑:程序博客网 时间:2024/06/06 08:37

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.

import java.util.HashMap;import java.util.Map;public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {               if (nums == null || nums.length < 2 || k < 1) {            return false;        }        Map<Integer, Integer> map = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            // 如果没有对应的key添加进去            if (!map.containsKey(nums[i])) {                map.put(nums[i], i);            }            // 已经有对应的key-value对            else {                // 原来保存的值对应的下标,它一定小于现在的下标                int value = map.get(nums[i]);                if (i - value <= k) {                    return true;                }                map.put(nums[i], i);            }        }        return false;    }}