Created
December 3, 2018 07:06
-
-
Save XcqRomance/a92fa33836587e9bdf34d70c43630523 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 4.存在重复 方法一暴力方法 | |
bool containsDuplicate(int* nums, int numsSize) { | |
if (numsSize <= 1) { | |
return false; | |
} | |
for (int i = 0; i < numsSize; i ++) { | |
for (int j = i+1; j < numsSize; j++) { | |
if (nums[i] == nums[j]) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
// 方法二 哈希表,数组的下表当作key,value是这个数字出现的次数 | |
bool containsDuplicate1(int* nums, int numsSize) { | |
if (numsSize<2) | |
return false; | |
int min=nums[0],max=nums[0]; | |
for (int i=1;i<numsSize;i++){ | |
if (min==nums[i]||max==nums[i]) | |
return true; | |
min=(nums[i]<min)?nums[i]:min; | |
max=(nums[i]>max)?nums[i]:max; | |
} | |
int index[999999] = {0}; | |
for (int i=0;i<numsSize;i++){ | |
if(index[nums[i]-min]!=0) | |
return true; | |
else | |
index[nums[i]-min]++; | |
} | |
return false; | |
} | |
int cmp(void const *a,void const *b); | |
// 方法三先排序后判断 | |
bool containsDuplicate2(int* nums, int numsSize) { | |
if ((numsSize == 0) || (numsSize ==1)) { | |
return false; | |
} | |
qsort(nums, numsSize, sizeof(nums[0]), cmp); | |
for (int i = 0; i < numsSize; i++) { | |
if (nums[i] == nums[i+1]) { | |
return true; | |
} | |
} | |
return false; | |
} | |
int cmp(void const *a,void const *b) { | |
return *(int*)a - *(int*)b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment