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; } }