Contains Duplicate II

Given an array of integers and an integerk, find out whether there are two distinct indicesiandjin the array such that nums[i] = nums[j] and the absolute difference betweeniandjis at mostk.

Example 1:

Input: 
nums = 
[1,2,3,1]
, k = 
3
Output: 
true

Example 2:

Input: 
nums = 
[1,0,1,1]
, k = 
1
Output: 
true

Example 3:

Input: 
nums = 
[1,2,3,1,2,3]
, k = 
2
Output: 
false

Solution

Using HashSet

O(min(n,k))) space - O(n) time

基本思想是维持一个k大小的窗口,用hashset记录其中的数,如果hashset的大小超过了k就从中删除最远的那个数,如果hashset出现有当前数字,那么就返回true

@san89kalp Explanation: It iterates over the array using a sliding window. The front of the window is at i, the rear of the window is k steps back. The elements within that window are maintained using a Set. While adding new element to the set, if add() returns false, it means the element already exists in the set. At that point, we return true. If the control reaches out of for loop, it means that inner return true never executed, meaning no such duplicate element was found.

public boolean containsNearbyDuplicate(int[] nums, int k) {
    Set<Integer> set = new HashSet<>();
    for (int i = 0; i < nums.length; ++i) {
        if (set.contains(nums[i])) return true;
        set.add(nums[i]);
        if (set.size() > k) {
            set.remove(nums[i - k]);
        }
    }
    return false;
}

https://leetcode.com/problems/contains-duplicate-ii/discuss/61372/Simple-Java-solution

HashMap

O(n) space - O(n) time

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                int idx = map.get(nums[i]);
                if (i - idx <= k) {
                    return true;
                }
            }
            map.put(nums[i], i);
        }

        return false;
    }
}

results matching ""

    No results matching ""