LeetCode 219. Contains Duplicate II

本文深入解析了LeetCode上的一个进阶版问题,即在给定数组和整数k的情况下,判断是否存在两个不同的索引i和j,使得nums[i]=nums[j]且|i-j|<=k。通过使用哈希映射实现高效的查找和更新,该题解展示了算法的优化过程。详细介绍了如何利用HashMap进行空间和时间复杂度的平衡,最终达到O(n)的时间复杂度和O(n)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/contains-duplicate-ii/

题目:

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.

题解:

Contains Duplicate的进阶版题目,类似题目还有Contains Duplicate III.

建立一个HashMap hm, key是nums[i], value 是 index i.

对于nums[i], 检查它时候在 hm中,若不在,就加<nums[i], i>进去. 

若是nums[i] 在 hm 中,就要看当前的i 和 hm中对应nums[i]的 value 的差值是否比k大:

若是比k 大,说明不符合条件,去掉旧的pair,添加当前pair.

若是不比k大,则return true.

这里熟练几个 HashMap functions: hm.put(key, value); hm.get(key); hm,remove(key): hm.containsKey(key).

Time Complexity: O(n). Space: O(n).

AC Java:

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         if(nums == null || nums.length == 0){
 4             return false;
 5         }
 6         HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
 7         for(int i = 0; i<nums.length; i++){
 8             if(!hm.containsKey(nums[i])){
 9                 hm.put(nums[i],i);
10             }else if(i - hm.get(nums[i]) > k){
11                 hm.put(nums[i], i);
12             }else{
13                 return true;
14             }
15         }
16         return false;
17     }
18 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825065.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值