Numbers that disappear (requires time complexity O(N))

Disappearing numbers

Subject requirements:

The array nums contains all integers from 0 to n, but one is missing. Please write code to find the missing integer. Can you do it in O(n) time?

Problem analysis:

When solving this problem, there are many different solutions on the Internet, such as using a hash table, etc., but for this problem, without requiring space complexity, we directly use the mapping method, compared to the original array , We create an array that theoretically includes all 0~N, and initialize it to (N+1), or other numbers outside of 0-N (for distinguishing), and then traverse the original array to change The value of the original array element corresponds to the subscript of the created array, and its value is set to 0, and then the array is traversed again. If it is not 0, it is a missing number, which can meet the requirements of the question.
The detailed code is as follows:

#include<stdio.h>
#define N 10//比N多一个

int main()
{
    
    
	int num[N] = {
    
     0, 1, 2, 8, 4, 5, 6, 9, 7, 3 };//理论上0-n元素共n+1数据,但只使用了n个空间
	int num1[N + 1];
	for (int i = 0; i < N + 1; ++i)
	{
    
    
		num1[i] = N + 1;
	}
	for (int i = 0; i < N; ++i)
	{
    
    
		num1[num[i]] = 0;
	}
	for (int i = 0; i < N + 1; ++i)
	{
    
    
		if (num1[i] == N + 1)
		{
    
    
			printf("the number is %d", i);
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/dream_i_success/article/details/110758576