title: Daily practice (25): Missing numbers from 0 to n-1
categories:[Swords offer]
tags:[Daily practice]
date: 2022/02/24
Daily practice (25): Missing numbers from 0 to n-1
All numbers in an increasing sorted array of length n-1 are unique, and each number is in the range 0 to n-1. Among the n numbers in the range 0~n-1, there is only one number that is not in the array, please find the number.
Example 1:
Input: [0,1,3]
Output: 2
Example 2:
Input: [0,1,2,3,4,5,6,7,9]
Output: 8
limit:
1 <= array length <= 10000
Source: LeetCode
Link: https://leetcode-cn.com/problems/que-shi-de-shu-zi-lcof
Method 1: Binary search
To find the boundary by bisection is actually to find the range boundary of the element equal to target
in the array. If there is no element equal to target
in the array, the value of the left and right boundaries obtained is the same.
int missingNumber(vector<int>& nums) {
int l = 0;
int r = nums.size();
int m = 0;
while (l < r) { //二分查找
m = (l + r) / 2;
if (nums[m] == m) {
l = m + 1;
} else {
r = m; //得到缺失的那个数
}
}
return r;
}
Method 2: Mathematical method (arithmetic sequence)
There are n numbers in the array, but there are n+1 numbers from 0 to n, and sum = (0+n)*(n+1)/2
can be obtained by summing the arithmetic sequence
Then the sum minus all the numbers in the array is the missing number
int missingNumber(vector<int>& nums) {
int n = nums.size();
int sum = (0 + n)*(n + 1) / 2; //等差数列求和
for (int i : nums) {
sum -= i; //总和减去数组所有数,就是缺失的那个数
}
return sum;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。