题目描述:
Given N integers, you are supposed to find the smallest positive integer that is NOT in the given list.
输入格式:
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.
输出格式:
Print in a line the smallest positive integer that is missing from the input list.
输入样例:
10 5 -25 9 6 1 3 4 2 5 17
输出样例:
7
题目翻译:
第一行给出一个正整数N <10^5
然后在第二行输入N个整数
要求输出一个没有在第二行被输入过的最小正整数
思路分析:
第一眼看到这道题想到的肯定是遍历
但是这终究是一个甲级的题
所以遍历应该会超时(并没有实验)
然后很容易想到的思路是:用空间换时间
思路是在输入N个数之前就创建一个足够大的数组 a[1000000]这种
然后判断每一个输入的数
如果这个数是正整数 就把对应的下标元素加一
比如说输入的是20
那么就另a[20]++
这样一来输入结束之后数组中就存储了每一个数出现的次数
没有出现的数的下标自然为0
这时再从下标为1开始遍历数组 找到第一个元素为0的下标
即为没有出现过的最小正整数
AC代码:
#include<stdio.h> int a[1000000]; int main() { 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; } } } }
这道题有两个坑需要注意:
1.PAT官网倒数第二个测试点应该没有输入任何正整数 所以这种情况下应该输出1
2.PAT官网最后一个测试点一直报段错误 应该是给出了一个极大极大的数 导致虽然数组已经很大了
但是还是超出了数组的范围 不过因为我们需要输出的是最小的那个正整数
所以只需要在进数组的时候 在判断是否是正数的同时加一个条件 稍微限制一下数的上限即可