1. 程式人生 > >pta 1144 The Missing Number

pta 1144 The Missing Number

Given N integers, you are supposed to find the smallest positive integer that is NOT in the given list.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​5​​). Then N integers are given in the next line, separated by spaces. All the numbers are in the range of int

.

Output Specification:

Print in a line the smallest positive integer that is missing from the input list.

Sample Input:

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

Sample Output:

7

題目大意:給定n個數,找出這n個數裡丟失的最小的正整數

注意細節:

(1)可能n個數全是負數,輸出1

(2)正整數要從1開始記錄,數中可能存在重複的數

(3)可能n個數都是連續的正整數,且從1開始,那麼輸出最大的數+1

程式碼如下:

#include<bits/stdc++.h>
using namespace std;
int a[1000002];
int main()
{
	int n;
	while(cin >> n)
	{
		for(int i = 0;i < n;i ++)
		{
			cin >> a[i];
		}
		sort(a,a + n);
		int i,fl = 0;
		for(i = 0;i < n - 1;i ++)
		{
			if(a[i] > 0)
			{
				if(a[i] == 1)
				fl = 1;
				if(fl)
				{
					if(a[i] == a[i + 1] || a[i + 1] == a[i] + 1)
					continue;
					else
					{
						cout << a[i] + 1 << endl;
						break;
					}
				}
				else
				{
					cout << fl + 1 << endl;
					break;
				}
			}
		}
		if(i == n - 1)
		{
			if(a[n - 1] > 0)
			cout << a[n - 1] + 1 << endl;
			else
			cout << 1 << endl;
		}
	}
	return 0;
}