Topic description:
Given N integers, you are supposed to find the smallest positive integer that is NOT in the given list.
Input format:
Each input file contains one test case. For each case, the first line gives a positive integer N (<= 105). Then N integers are given in the next line, separated by spaces. All the numbers are in the range of int.
Output format:
Print in a line the smallest positive integer that is missing from the input list.
Input sample:
10 5 -25 9 6 1 3 4 2 5 17
Sample output:
7
Topic translation:
The first line gives a positive integer N < 10^5
Then enter N integers on the second line
Ask to output the smallest positive integer not entered on the second line
Thought analysis:
The first time I saw this question, I must have thought of traversing
But it's an A-level question after all.
So the traversal should time out (and did not experiment)
Then it is easy to think of the idea is: use space for time
The idea is to create a large enough array a[1000000] before entering N numbers.
Then determine the number of each input
If the number is a positive integer, add one to the corresponding subscript element
For example, enter 20
Then another a[20]++
In this way, the number of occurrences of each number is stored in the array after the input is completed.
The subscript of the number that does not appear is naturally 0
At this time, traverse the array starting from subscript 1 to find the subscript whose first element is 0
is the smallest positive integer that has never appeared
AC code:
#include<stdio.h> int a[1000000]; intmain() { int temp=0; int n=0; int flag=0; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&temp); if(temp>0&&temp<1000000) { flag=1; a[temp]++; } } if(flag==0) { printf("1"); } else { for(int i=1;i<1000000;i++) { if(a[i]==0) { printf("%d",i); break; } } } }
There are two pitfalls to note in this question:
1. The penultimate test point of the PAT official website should not input any positive integer, so it should output 1 in this case
2. The last test point of the PAT official website has been reporting a segmentation fault, which should be a very large number, although the array is already very large
But it still exceeds the range of the array, but because we need to output the smallest positive integer
So you only need to add a condition to slightly limit the upper limit of the number when judging whether it is a positive number when entering the array