LeetCode & Q219-Contains Duplicate II

Array Hash Table

Description:

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

本来继续沿用I里的HashSet,奈何用的不熟,不会用....

用了HashMap,发现网上很多人跟我用的一样,明明是通过不了的,也不知道他们是怎么通过的....

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

测试用例:[1,0,1,1] 1 无法通过

参考了HashSet方法,设置了一个长度为k的窗口,通过移动窗口来确定是否满足条件,好机智!

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<Integer>();  
        int start = 0, end = 0;
        for(int i = 0; i < nums.length; i++) {
            if(!set.contains(nums[i])) {    
                set.add(nums[i]);   
                end++;
            } else { 
                return true;
            }
        
            if(end - start > k) {    
                set.remove(nums[start]);
                start++;
            }  
        }  
        return false;
    }
}
原文地址:https://www.cnblogs.com/duyue6002/p/7210400.html