二分查找:
c++
class Solution {
public:
int missingNumber(vector<int>& nums) {
int i = 0;
int j = nums.size()-1;
while(i<=j){
int m = (i+j)/2;
if(nums[m] == m){
i=m+1;
}else if(nums[m] > m){
j=m-1;
}
}
return i;
}
};
python
class Solution:
def missingNumber(self, nums: List[int]) -> int:
i=0
j=len(nums)-1
while i<=j:
m = (i+j)//2
if nums[m] == m:
i=m+1
elif nums[m] > m:
j=m-1
return i