首页 > 其他 > 详细

Contains Duplicate II LT219

时间:2019-05-12 10:03:49      阅读:114      评论:0      收藏:0      [点我收藏+]

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.

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

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

Time complexity: O(N)

Space complexity: O(k+1)

 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), 

Time complexity: O(N)

Space complexity: O(N)

 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 }
 

Contains Duplicate II LT219

原文:https://www.cnblogs.com/taste-it-own-it-love-it/p/10851005.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!