Missing number of leetcode

Time:2022-7-6

order

This article mainly records the missing numbers of leetcode

subject

Given an array num containing N numbers in [0, n], find the number that does not appear in the array within the range of [0, n].

 

Advanced:

Can you solve this problem by implementing an algorithm with linear time complexity and only using additional constant space?
 

Example 1:

Input: num = [3,0,1]
Output: 2
Explanation: n = 3, because there are 3 numbers, all numbers are in the range [0,3]. 2 is the missing number because it does not appear in nums.
Example 2:

Input: num = [0,1]
Output: 2
Explanation: n = 2, because there are 2 numbers, all numbers are in the range [0,2]. 2 is the missing number because it does not appear in nums.
Example 3:

Input: num = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9, because there are 9 numbers, all numbers are in the range [0,9]. 8 is the missing number because it does not appear in nums.
Example 4:

Input: num = [0]
Output: 1
Explanation: n = 1, because there is 1 number, all numbers are in the range [0,1]. 1 is the missing number because it does not appear in nums.
 

Tips:

n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
All numbers in nums are unique

Source: leetcode
Link: https://leetcode-cn.com/problems/missing-number
The copyright belongs to LinkedIn. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution

class Solution {
    public int missingNumber(int[] nums) {
        int result = nums.length;
        for (int i = 0; i < nums.length; ++i){
            result ^= nums[i];
            result ^= i;
        }
        return result;
    }
}

Summary

Use hereAll numbers in nums are uniqueThis condition uses XOR operation to calculate the index and value of the array, and the result of traversal is the missing number.

doc

  • Missing numbers