题目描述
从0,1,2,...,n这n+1个数中选择n个数,找出这n个数中缺失的那个数,要求O(n)尽可能小。
方法一
int solve(int* a, int aLen) {
int num = 0;
for (int i = 0; i < aLen; ++i) {
num ^= i;
num ^= a[i];
}
num ^= aLen;
return num;
}
方法二
int solve(int* a, int aLen) {
int IN=a[0];
for(int i=0;i<aLen;i++){
if(a[i]!=IN)
return a[i]-1;
IN++;
}
方法三
int solve(int* a, int aLen) {
// write code here
int left = 0, right = aLen-1;
while(left < right){
int mid = left + ((right-left) >> 1);
if(a[mid] == mid){
left = mid + 1;
}else if(a[mid] > mid){
right = mid;
}
}
return right;
//return a[right] > right ? right: aLen+1;
}