[Data structure] Leedcode disappearing numbers (interview questions)

Table of contents

          1. Topic Description

          2. Topic Analysis


1. Topic Description 

Topic Link: Leetcode Disappearing Numbers

The array nums contains all integers from 0 to n, but one of them is missing. Please write code to find that missing integer. Do you have a way to do it in O(n) time? 

Example 1:

Input: [3,0,1]

Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]

Output: 8 

2. Topic Analysis 

method 1:

We can add the numbers from 0 to n, then subtract the input numbers, and the final returned result is what we want.

int missingNumber(int* nums, int numsSize) 
{
    int N = numsSize;
    int ret = N * (N + 1) / 2;//0-n之间所有整数和
    for (int i = 0; i < numsSize; ++i)
    {
        ret -= nums[i];
    }
    return ret;
}

The time complexity is: O(N).

Method 2:

First set a hypothetical missing number x=0, let x be XORed with all the numbers from 0-n first, and x be XORed with each number in the array, and the final value of x is the missing number.

First popularize it:

The result of XORing two identical numbers is 0.

XORing 0 with any number is still the number itself.

int missingNumber(int* nums, int numsSize) 
{
    int N = numsSize;
    int x = 0;// 缺失的数字
    for (int i = 0; i < N; ++i)//先和数组里面的数字异或
    {
        x ^= nums[i];
    }
    for (int j = 0; j < N + 1; ++j)//再和0-n之间的数字异或
    {
        x ^= j;
    }
    return x;
}

The time complexity is: O(N).


This article provides two methods, and there should be other optimal solutions. You are welcome to comment below and help each other improve together.

If there are deficiencies in this article, you are welcome to comment below, and I will correct it as soon as possible.

 Old irons, remember to like and pay attention!!!

Guess you like

Origin blog.csdn.net/m0_63198468/article/details/128461326