Contains Duplicate

本文介绍两种检查整数数组中是否存在重复元素的方法。第一种方法采用双重遍历对比的方式,时间复杂度为O(n^2);第二种方法通过哈希表记录每个元素出现次数,时间复杂度降低到O(n),并详细解释了实现过程。

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

given an array of integers, find if the array contains any duplicates.
your function should return true if any value appears at least twice in the array, 

and it should return false if every element is distinct.

//solution1 time(O(n^2))
bool containsDuplicate1(int* nums, int numsSize) {
	int* p = nums;
	int* q = nums + numsSize - 1;
	int* cursor = NULL;
	bool result = true;
	while (q - p>0)
	{
		cursor = p + 1;
		while (q - cursor >= 0)
		{
			if (*cursor == *p)
				return true;
			else
			{
				++cursor;
			}
		}
		++p;
	}
	return false;

}

//solution2 time(O(n))
bool containsDuplicate2(int* nums, int numsSize) {
	bool result = true;
	if (numsSize == 0)
		result = false;
	int hashkey[numsSize];
	int hashvalue[numsSize];
	for (int k = 0; k != numsSize; ++k)
		hashvalue[k] = 0;

	for (int i = 0; i != numsSize; ++i)
	{
		int id = (nums[i] + numsSize) % numsSize;
		if (hashvalue[id] == 0)
		{
			++hashvalue[id];
			hashkey[id] = nums[i];
		}
		else if (hashkey[id] == nums[i])
			++hashvalue[id];
		else
		{
			while (hashvalue[id] != 0)
			{
				id = (id + 1) % numsSize;
			}
			hashkey[id] = nums[i];
			hashvalue[id] += 1;
		}
	}
	for (int j = 0; j != numsSize; ++j)
	{
		if (hashvalue[j] >= 2)
		{
			result = true;
			break;
		}
		else
			result = false;
	}
	return result;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值