Java solution using HashMap's put()


  • 17
    V
    public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    	
    	for(int i = 0; i <  nums.length; i++) {
    		Integer ord = map.put(nums[i], i);
    		if(ord != null && i - ord <= k) {
    			return true;
    		}
    	}
    	
    	return false;
    }
    

    }


  • 0
    S

    Awesome approach!! Generally people forget that map.put() can return also :P :P


  • 0
    V
    This post is deleted!

Log in to reply
 

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