[219] Contains Duplicate II
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i andj is at most k.
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { //用map存储数组元素和下标,看是否存在与当前元素相等且下标之差小于等于k的元素,存在则返回true;否则将当前元素和其下标存入map。 Map<Integer,Integer> map=new HashMap<Integer,Integer>(); if(nums==null||nums.length<=0) return false; for(int i=0;i<nums.length;i++){ if(!map.isEmpty()&&map.containsKey(nums[i])){ int end=map.get(nums[i]); if(i-end<=k) return true; else map.put(nums[i],i); }else{ map.put(nums[i],i); } } return false; } }