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.
思路:
1. 将数组进行排序,这样可以保证相同的元素出现在相邻的位置
2. 顺序遍历发现有重复则返回TRUE
直接上code:
int cmp(const void *a, const void *b){
return (*((int*)a) > *((int*)b));
}
bool containsDuplicate(int* nums, int numsSize) {
int i = 0;
if (numsSize <= 0)
return false;
//sort firstly
qsort(nums, numsSize, sizeof(int), cmp);
for(i = 0; i < numsSize - 1; i ++)
{
if (*(nums + i) == *(nums + i + 1))
{
return true;
}
}
return false;
}