Why case [1, 0, 1, 1] and 1 should be true?


  • 0
    L

    As title, and below is my code using HashMap. Thanks.

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
    
            Map<Integer, Integer> map = new HashMap<>();
            
            int max = 0;
            boolean dupe = false;
            
            for(int i = 0; i < nums.length; i ++) {
                if (map.containsKey(nums[i])) {
                    dupe = true;
                    max = Math.max(max, i - map.get(nums[i]));
                } else {
                    map.put(nums[i], i);
                }
            }
            return max <= k && dupe;
        }
    }

  • 2
    E

    because index 2 and 3 have equal values. This 3-2 is equal to 1 and the k value here is 1. the requirement here said at most K. so 1 is at most 1 and therefore this is true.

    shouldn't your code be looking for the closest duplicate which would be the Min?


Log in to reply
 

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