Java solution using HashMap


  • 0
    Q
    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k){
    		Map<Number, Number> map = new java.util.HashMap<Number, Number>();
    		for (int i=0;i<nums.length;i++){
    			int val = nums[i];
    			
    			Number n = new Number();
    			n.value = val;
    			n.index = i;
    			
    			Number exist = map.get(n);
    			if (exist == null){
    				map.put(n, n);
    			}
    			else{
    				int index = exist.index;
    				if (i-index  <= k){
    					return true;
    				}
    				exist.index = i;
    			}
    		}
    		return false;
    	}
    
    	private class Number{
    		int value;
    		int index;
    		
    		public boolean equals(Object o){
    			Number n = (Number)o;
    			return n.value == this.value;
    		}
    		public int hashCode(){return value;}
    	}
    }

Log in to reply
 

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