https://leetcode.com/problems/contains-duplicate/
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.
方法一,想到的简单方法
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
bool containsDuplicate(int* nums, int numsSize) {
int i;
//
qsort(nums, numsSize, sizeof(nums[0]), cmp);
for(i = 1; i < numsSize; ++i) {
if(nums[i] == nums[i-1])
return true;
}
return false;
}
方法二,基于插入排序改进,效率更高
bool containsDuplicate(int* nums, int numsSize) {
int i, j, key;
for(i = 1; i < numsSize; ++i) {
j = i -1;
key = nums[i];
while(j > 0 && nums[j] > key) {
nums[j + 1] = nums[j]; // move to back
j--;
}
if(j != (i-1))
nums[j + 1] = key;
if(nums[j] == key)
return true;
}
return false;
}

本文介绍了在整数数组中查找重复元素的两种方法:一种是通过排序后比较相邻元素来实现;另一种则是利用插入排序过程中的比较进行优化,提高了查找效率。
263

被折叠的 条评论
为什么被折叠?



