头图

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;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记