从零开始的LC刷题(53): Contains Duplicate II 查找重复元素2

该博客介绍了如何使用C++解决LeetCode第53题——查找数组中绝对差值不超过k的重复元素问题。通过示例说明了题目需求,并分享了两种不同的解决方案,包括使用map存储元素上一次出现位置的方法,以及一种高效的哈希表实现,这两种方法都显著优于大部分在线提交的C++代码在时间和内存上的表现。

摘要生成于 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.

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

这个和上一个题相比麻烦就麻烦在要存储这个数上一次出现的位置,为此不得不看了看map的用法,结果:

Success

Runtime: 28 ms, faster than 93.62% of C++ online submissions for Contains Duplicate II.

Memory Usage: 15.4 MB, less than 24.76% of C++ online submissions for Contains Duplicate II.

代码:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int> lib;
        for(int i=0;i<nums.size();i++){
            if(lib[nums[i]]&&i-lib[nums[i]]<k){return true;}
            lib[nums[i]]=i+1;
        }
        return false;
    }
};

这次终于偷偷发现一个牛逼的结果,在details里找到的,手打的hash,给大家参考一下:

Success

Runtime: 20 ms, faster than 99.48% of C++ online submissions for Contains Duplicate II.

Memory Usage: 11.4 MB, less than 95.24% of C++ online submissions for Contains Duplicate II.

#define HASHSIZE 10009
#define NUMSIZE 100009
int hashTable[HASHSIZE];
long long getHash(long long n){
	if (n < 0) n = -n;
	return n% HASHSIZE;
}
struct node{
	int value;
	int next;
};

struct node arr[NUMSIZE];

class Solution {
public:
	bool containsNearbyDuplicate(vector<int>& nums, int k) {
		int len = nums.size();

		int i,j,key;
		for (i = 0; i < HASHSIZE; i++)
			hashTable[i] = -1;
		
		for (i = 0; i < len; i++){
			key = getHash((long long)nums[i]);
			if (hashTable[key] < 0){
				hashTable[key] = i;
				arr[i].value = nums[i];
				arr[i].next = -1;
			}
			else{
				j = hashTable[key];
				while (j >= 0){
					if (nums[i] == arr[j].value && abs(i - j) <= k) return true;
					j = arr[j].next;
				}
				arr[i].next = hashTable[key];
				arr[i].value = nums[i];
				hashTable[key] = i;
			}
		}
		return false;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值