My Java solution


  • 0
    H
    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            int min=0;
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int i = 0; i<nums.length; i++){
                if(map.containsKey(nums[i])==false)
                    map.put(nums[i],i);
                else{
                    int difference = i- map.get(nums[i]);
                    if(min == 0){
                        min = difference;
                        map.put(nums[i],i);
                    }
                    else if(difference < min){
                        if(difference<k)
                            return true;
                        min = difference;
                        map.put(nums[i],i);
                    }
                       
                }
            }
            if(min>k || min==0)
                return false;
            else
                return true;//要求得有相同的两个,还得小于。没有相同的两个都不行
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.