网址:https://leetcode.com/problems/contains-duplicate/
Total Accepted: 71959
Total Submissions: 178180
Difficulty: Easy
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.
我的AC:
bool containsDuplicate(int* nums, int numsSize) {
int i, j;
for(i = 0; i < numsSize ; i ++){
for(j = i + 1 ; j <numsSize; j++){
if (nums[i] == nums[j])
return true;
}
}
return false;
}
缺点:1568ms。时间太长。如果先把nums数组排序再进行比较,就快的多了(仅需比较相邻的是否相同)。
改进:
int comp(const int *a, const int *b) {
if (*a > *b) return 1;
else if (*a < *b) return -1;
else return 0;
}
bool containsDuplicate(int* nums, int numsSize) {
if (numsSize < 2) {
return false;
}
qsort(nums, numsSize, sizeof(int), comp);
for (int i = 0; i < numsSize - 1; i++) {
if (nums[i] == nums[i+1]) {
return true;
}
}
return false;
}
其中comp函数也可以写成:
int comp (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
本文介绍了一种解决LeetCode上217题含有重复元素的方法,通过双重循环检查数组中是否存在重复元素,并提出了通过排序来优化算法效率的方案。

2060

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



