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 difference between i and j is at most k.java
给定一个整数数组nums与一个整数k,当且仅当存在两个不一样的下标i和j知足nums[i] = nums[j]而且|i-j|<=k时返回true,不然返回false。算法
对nums[0…n-1],存入一个map中,(muns[i], i),若是键nums[k]已经存在,则比较以前的下标和如今的下标的差值,若是差值不大于k,说明到了知足条件的两个值,不然使用新的下标做为值数组
算法实现类spa
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; } }