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 (≤105). 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,开始的时候将vector数组初始化为-1,给出的数字为正数且小于等于N时,令v[N] = 1.最后遍历V数组,输出第一个遇到的-1的下标.若整个V数组都为1,则输出N+1.

 

Code:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n, t;
    cin >> n;

    vector<int> v(n + 1, -1);
    for (int i = 0; i < n; ++i) {
        cin >> t;
        if (t > 0 && t <= n) v[t] = 1;
    }
    bool found = false;
    for (int i = 1; i <= n; ++i) {
        if (v[i] < 0) {
            cout << i << endl;
            found = true;
            break;
        }
    }
    if (!found) cout << n + 1 << endl;

    return 0;
}

 

posted @ 2020-04-14 16:53  Veritas_des_Liberty  阅读(195)  评论(0编辑  收藏  举报