Java Code Using HashMap, took me much time

  • 0
    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            int len = nums.length;
            HashMap<Integer,Integer> hashMap = new HashMap<>();
            for(int i = 0; i< len; i++){
                if(!hashMap.containsKey(nums[i])) hashMap.put(nums[i],i);
                else if(i - hashMap.get(nums[i]) <= k) return true;
                else hashMap.replace(nums[i],i);
            return false;

Log in to reply

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