假設1-10000裏有一個數字缺失,現在有9999個無序數字,如何快速定位這個數字?
1如果數組是有序的,可以採用快排方法,但是這個方法沒有針對性,時間複雜度爲O(nlogn)
2使用作何再做差的方法
result = sum(1-10000) - sum(a[0]-a[9998])
這種方法的複雜度爲O(n)但是有可能溢出,缺乏魯棒性。
3轉化爲find single number的方法,複雜度爲O(n)
代碼如下
int FindMissingNum( int numbers[] , int len){
int i,result;
if( numbers == NULL || len < 2)
return ERROR;
result = numbers[0];
for(i = 1; i != len; i++){
result ^= i;
result ^= numbers[i];
}
result ^= len;
result ^= (len+1);
return result;
}