Leetcode ☞ 217. Contains Duplicate
2016-02-27 23:23
465 查看
网址:https://leetcode.com/problems/contains-duplicate/
My Submissions
Question
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:
缺点: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 );
}
217. Contains Duplicate
My SubmissionsQuestion
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 );
}
相关文章推荐
- 【UVa】11413 – Fill the Containers
- GCJ--Millionaire (2008 APAC local onsites C)
- 关于main主函数的两个参数argc和argv
- ZOJ 3781 Paint the Grid Reloaded 图论 bfs
- 11.2 RAC: In "crsctl stat res -t" State Details May Be Missing or Incorrect (文档 ID 1086563.1)
- Hanoi Tower Troubles Again! (找规律)
- GetPostBackEventReference加RaisePostBackEvent实现自定义控件中回调传参
- Codeforces - AIM Tech Round (Div. 2)C - Graph and String
- ZOJ 3780 Paint the Grid Again
- 使用Keychain配置
- Leet Code OJ 70. Climbing Stairs [Difficulty: Easy]
- 1021 Fibonacci Again
- 集训队专题(7)1001 Drainage Ditches
- train validation test
- 1090 Higest Price in Supply Chain
- 102.Daikon Forge基础使用label、button、sprite、textureAtlas、font
- UVA 10976(p183)----Fractions Again?!
- VS2012 error C2664: “std::make_pair”:无法将左值绑定到右值引用
- 101.Daikon Forge插件介绍和安装
- 格式化数据#8: AIE实验室交流群推荐的相关书籍(附豆瓣链接和ISBN)