一個長度爲n-1的遞增排序數組中的所有數字都是唯一的,並且每個數字都在範圍0~n-1之內。在範圍0~n-1內的n個數字中有且只有一個數字不在該數組中,請找出這個數字。
示例 1:
輸入: [0,1,3]
輸出: 2
示例 2:
輸入: [0,1,2,3,4,5,6,7,9]
輸出: 8
限制:
1 <= 數組長度 <= 10000
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析:
二分法
解答:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int i = 0;
int j = nums.size()-1;
int m;
while(i<=j){
m = i + (j-i)/2;
if(nums[m]==m){
i = m + 1;
}
else{
j = m-1;
}
}
return i;
}
};