Simple solution. O(n) time and space complexity. Java HashMap.


  • 0
    O
    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            int i = 0;
            boolean contains;
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for(i = 0; i < nums.length; i++) {
                contains = map.containsKey(nums[i]);
                if (contains && i - map.get(nums[i]) <= k) {
                    return true;
                } else {
                    map.put(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.