Contains Duplicate II LT219

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.spa

Example 1:code

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

Example 2:blog

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

Example 3:rem

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

Idea 1. Sliding window + HashMap(Set), note there are k+1 values in the window for [0, k].get

Time complexity: O(N)input

Space complexity: O(k+1)it

 1 class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         Set<Integer> cache = new HashSet<>();
 4         
 5         for(int right = 0; right < nums.length; ++right) {
 6             if(right >= k+1) {
 7                 cache.remove(nums[right - (k+1)]);
 8             }
 9             
10             if(cache.contains(nums[right])) {
11                 return true;
12             }
13             cache.add(nums[right]);
14         }
15         
16         return false;
17     }
18 }

Idea 1.b HashMap with index, pair (nums[i], i), io

Time complexity: O(N)class

Space complexity: O(N)im

 1 class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         Map<Integer, Integer> cache = new HashMap<>();
 4         
 5         for(int i = 0; i < nums.length; ++i) {
 6             Integer prev = cache.get(nums[i]);
 7             if(prev != null && i - prev <= k) {
 8                 return true;
 9             }
10             cache.put(nums[i], i);
11         }
12         
13         return false;
14     }
15 }
相關文章
相關標籤/搜索