PAT 1144 The Missing Number[简单]

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 (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个整数,找到不在其中的最小的正整数。

//猛一看感觉很简单,第一次提交,有3个测试点没通过:

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;

map<int,int>mp;
int main()
{
    int n,temp;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>temp;
        if(temp<0&&mp[-temp]!=1)
            mp[-temp]=2;//2表示当前以负数形式出现。
        else
            mp[temp]=1;
    }
    for(int i=1;i<=n;i++){
        if(mp[i]==2||mp[i]==0){
            cout<<i;break;
        }
    }
    return 0;
}
View Code

//利用map的按照关键字自排序特性,写成了这样,还是2,3,5测试点过不去,想不出来哪里错了。

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;

map<int,int>mp;
int main()
{
    int n,temp;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>temp;
        if(temp<0&&mp[-temp]!=1)
            mp[-temp]=2;//2表示当前以负数形式出现。
        else
            mp[temp]=1;
    }
//    for(int i=1;i<=n;i++){
//        if(mp[i]==2||mp[i]==0){
//            cout<<i;break;
//        }
//    }
    int ct=1;
    for(auto it=mp.begin();it!=mp.end();it++){
        //cout<<it->first<<" "<<it->second<<'
';
        if(it->first==ct&&it->second!=2)ct++;//按照自排序特性,判断是否相等。
        else{
            cout<<ct;break;
        }
    }
    return 0;
}
View Code

代码转自:https://www.liuchuo.net/archives/4662

#include <iostream>
#include <map>
using namespace std;
int main() {
    int n, a, num = 0;
    cin >> n;
    map<int, int> m;
    for (int i = 0; i < n; i++) {
        cin >> a;
        m[a]++;
    }
    while(++num)
        if (m[num] == 0) break;
    cout << num;
    return 0;
}

//看完这个我才反应过来,map的关键字可以是负数的,又不是数组下标,你那么谨慎干什么。。

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;

map<int,int>mp;
int main()
{
    int n,temp;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>temp;
        mp[temp]=1;
    }
    //for(int i=1)//这里最好别用for循环,就while循环就可以,因为不太好控制上限,
    //有可能是int的最大值呢啊
    int num=0;
    while(++num){//这里真的还是++num最好,num++都需要-1的
            //很少用++num,学习了。
        if(mp[num]==0){
            cout<<num;break;
        }
    }
    return 0;
}

//学习了!