【Leetcode 217-存在重复元素 Contains Duplicate】(c语言版)

该博客主要介绍了如何使用C语言解决LeetCode的217题——检查整数数组中是否存在重复元素。博主通过分析题目,提出当数组元素数量小于2时的特殊情况,并采用排序后比较相邻元素来判断是否存在重复。博客包含题目示例、测试用例和完整的C语言代码实现。

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

目录

 

存在重复元素

测试单元

题目分析

代码表示

     大功告成


存在重复元素

给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回真。如果数组中每个元素都不相同,则返回错误。

示例1:

输入: [1,2,3,1]
输出: true//1

示例2:

输入: [1,2,3,4]
输出: false//0

示例3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

测试单元

就用由题目给出的测试用例:代码如下

int main()
{
	int nums1[4] = { 1, 2, 3, 1 };
	int nums2[4] = { 1, 2, 3, 4 };
	int nums3[10] = { 1, 1, 1, 3, 3, 4, 3, 2, 4, 2 };
	int ret1 = containsDuplicate(nums1, 4);  //返回0为没有重复,返回1为有重复
	int ret2 = containsDuplicate(nums2, 4);
	int ret3 = containsDuplicate(nums3, 10);
	printf("%d \n", ret1);
	printf("%d \n", ret2);
	printf("%d \n", ret3);
	system("pause");
	return 0;
}

题目分析

找数组中是否有重复项可按数元素数量分为两类:

1.没有或只有一个元素则直接返回0(没有重复项)

2.有多个元素(<2)则再进行判断

一,先将数组排一下序就可以很好的解决查看是否有重复项的问题了

湾将相邻的两个元素比较大小看是否相等,相等的化返回1(有重复项)

从头遍历比较到最后都没有的化,返回0(没有重复项)

代码表示

如下:排序的化我这里是运用了Ç库里的快排函数具体用法及介绍可以从MSDN中查看你也可以自己写一个排序方法(冒泡,堆排等都可以只要达到排序的目的。 ....)

#define _CRT_SECURE_NO_WARNINGS 1
#include"test.h"
int comp(const void *a, const void *b)//比较函数
{
	return *(int*)a - *(int*)b;
}
int containsDuplicate(int* nums, int numsSize)
{
	if (numsSize + 1 <= 2)//一个数或没有数时直接返回0没有重复
	{
		return 0;
	}
	qsort(nums, numsSize, sizeof(int), comp);//快排
	for (int i = 0; i < numsSize - 1; i++)//相邻筛选
	{
		if (nums[i] == nums[i + 1])
			return 1;
	}
	return 0;
}

int main()
{
	int nums1[4] = { 1, 2, 3, 1 };
	int nums2[4] = { 1, 2, 3, 4 };
	int nums3[10] = { 1, 1, 1, 3, 3, 4, 3, 2, 4, 2 };
	int ret1 = containsDuplicate(nums1, 4);
	int ret2 = containsDuplicate(nums2, 4);
	int ret3 = containsDuplicate(nums3, 10);
	printf("%d \n", ret1);
	printf("%d \n", ret2);
	printf("%d \n", ret3);
	system("pause");
	return 0;
}

     大功告成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值