Last active
April 25, 2019 14:38
-
-
Save necusjz/8aa1c6ddebdd9da390161900a1f6240d to your computer and use it in GitHub Desktop.
面试题 3.1:找出数组中重复的数字
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
bool duplicate(int numbers[], int length, int *duplication) { | |
if(numbers == nullptr || length <= 0) { | |
return false; | |
} | |
for(int i = 0; i < length; ++i) { | |
if(numbers[i] < 0 || numbers[i] > length-1) { | |
return false; | |
} | |
} | |
for(int i = 0; i < length; ++i) { | |
while(numbers[i] != i) { | |
if(numbers[i] == numbers[numbers[i]]) { | |
*duplication = numbers[i]; | |
return true; | |
} | |
int temp = numbers[i]; | |
numbers[i] = numbers[temp]; | |
numbers[temp] = temp; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment