Java solution using HashMap


  • 0
    J

    Here is a Java solution that stores the previous occurrence of given value in HashMap.


    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            if (nums == null || nums.length == 0 || k <= 0) {
                return false;
            }
    
            final Map<Integer, Integer> occurences = new HashMap<>();
            for (int ind = 0; ind < nums.length; ind++) {
                if (occurences.containsKey(nums[ind])) {
                    final int prev = occurences.get(nums[ind]);
                    if (ind - prev <= k) {
                        return true;
                    }
                }
                occurences.put(nums[ind], ind);
            }
            return false;
        }
    }

  • 0

    I think this is wrong, because you're not really storing the previous occurrence but only the first occurrence.


  • 0
    J

    Yes, you are right. The test cases seams to be wrong, since this code passes the tests.
    Corrected the implementation.


  • 0

    Thanks @pochmann for pointing this out! I think this is a common mistake, I have just added an additional test case to prevent it.


Log in to reply
 

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