目录
存在重复元素
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回真。如果数组中每个元素都不相同,则返回错误。
示例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;
}