[Leetcode] 219. Contains Duplicate II 解题报告

本文介绍了一种使用哈希表来解决寻找数组中是否存在两个不同索引的相同元素且索引差不超过k的问题的方法。通过记录每个数出现的位置,并在发现重复数值时检查索引差是否符合条件,以此达到O(n)的时间复杂度。

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

题目

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.

思路

思想和 [Leetcode] 217 Contains Duplicate非常类型,只需要稍稍做一下改进即可:我们在哈希表中同时记录数组中每个数出现的位置。一旦发现了值相同的数,还需要判断两者的索引差距是否在k之内。如果是则直接返回true,否则我们还需要修改该数的索引(因为我们是从前往后扫描的,所以修改后的索引会有利于后续再次发现相同的数时对索引差异的判断)。算法的时间复杂度和空间复杂度都是O(n)。

代码

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> hash;
    	unordered_map<int, int>::iterator it;
    	for (size_t i = 0; i < nums.size(); i++) {
    		it = hash.find(nums[i]);
    		if (it == hash.end()) {
    			hash.insert(pair<int, int>(nums[i], i));
    		}
    		else {
    			if (i - hash[nums[i]] <= k) {
    				return true;
    			}
    			it->second = i;
    		}
    	}
    	return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值