title: 剑指Offer 53-II. 0~n-1中缺失的数字(c语言)
一个长度为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 \leqslant 数组长度 \leqslant 10000
$$
法1:
int missingNumber(int* nums, int numsSize){
if(NULL==nums || numsSize<=0){
return -1;
}
int low=0, high=numsSize-1;
while(low <= high)
{
int mid = (low+high)>>1;
if(nums[mid] != mid){
if(0==mid || nums[mid-1]==mid-1){
return mid;
}
high = mid-1;
} else{
low = mid+1;
}
}
if(low == numsSize){
return numsSize;
}
return -1;
}
法2:
int missingNumber(int* nums, int numsSize){
int sum=0, result=0;
sum = numsSize*(numsSize+1)/2;
for(int i=0; i<numsSize; ++i)
{
result += nums[i];
}
return sum-result;
}
标签:numsSize,return,数字,Offer,int,nums,mid,53,II
From: https://www.cnblogs.com/blue-Suri/p/17342971.html