美文网首页
1144 The Missing Number(20 分)

1144 The Missing Number(20 分)

作者: _YuFan | 来源:发表于2018-08-12 23:25 被阅读0次

    1144 The Missing Number(20 分)

    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个数,输出不在给出的数中的最小正整数。
    分析:1.用set去接收这些数(排序+去重)
    题解:

    #include<cstdlib>
    #include<cstdio>
    #include<set>
    using namespace std;
    int main() {
        int n;
        set<int> s;
        scanf("%d", &n);
        for (int i = 0; i != n; i++) {
            int t;
            scanf("%d", &t);
            s.insert(t);
        }
        int pre = *(s.begin());
        for (set<int>::iterator it = ++s.begin(); it != s.end(); it++) {
            if (*it - pre != 1 && pre+1 > 0) {
                printf("%d", pre + 1);
                return 0;
            }
            pre = *(it);
        }
        //如果遍历到最后一个仍然找不到符合要求的结果,
        //则输出最大的数之后的正整数(最大的数可能为正,或者仍为负)
        if (pre >= 0) {
            printf("%d", pre + 1);
        }
        else {
            printf("%d", 1);
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:1144 The Missing Number(20 分)

          本文链接:https://www.haomeiwen.com/subject/cpwebftx.html