PAT 1144 C++ 版

1.题意

不再分析。

2.测试用例

10
5 -25 9 6 1 3 4 2 5 17

5
1 2 3 4 5


5
1 2 3 5 6

2 
1 -1

3.代码

#include<cstdio> 
#include<algorithm>
# define N 100001

int main(){
	int total;
	scanf("%d",&total);
	
	int i;
	int array[total];
	int result [total+2];//用于保存结果的数 
	int number;
	
	for(i = 1;i <= total + 1 ;i++){
		result[i] = i;
	}	
	
	//输入total 个整数 
	for(i = 0;i< total;i++){
		scanf("%d",&array[i]);
		if(array[i] > 0){//大于 0 
			if(array[i] <= total){ //小于total 
				result[array[i]] = 0;//说明这个整数出现过 
			}
		} 
	}
	
	for(i= 1;i < total + 2;i++){
		if(result[i] != 0){
			printf("%d\n",i);
			break;
		}
	}
}

4.执行结果

PAT 1144 C++ 版

5. 坑点

  • 如果当前全都是递增序列,那么输出的将是 total+1
    对应的测试用例就是:
2
1 2
  • 在c++中,如果没有给数组赋初始值,那么得到的值就是一个很变态的值。如下图所示:
    PAT 1144 C++ 版
    这和 java 有很大的不同,如果在java 里,会直接初始化为0,而不是其它值。
  • 注意 for循环中的判断条件的设置。
if(array[i] > 0){//大于 0 
	if(array[i] <= total){ //小于total 
		result[array[i]] = 0;//说明这个整数出现过 
	}
} 

相对于其它的代码,是一种优化,减少了比较次数。

相关文章: