# PAT - 1144 The Missing Number（20 分） || LeetCode 41. First Missing Positive

#### 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

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void test(vector<int> nums){
for(int i = 0; i < nums.size(); i++)
cout << nums[i] << " ";
cout <<  "-------------" << endl;
}

int main(){
vector<int> nums;
int len, number;
cin >> len;
if(len == 0){
cout << 1;
return 0;
}

while(len--){
cin >>  number;
nums.push_back(number);
}

sort(nums.begin(), nums.end());

bool index[nums.size()] = {false};
index[0] = true;

for(int i = 0; i < nums.size(); i++){
if(nums[i] <= 0)                 //小于等于0，跳过
continue;
if(nums[i] > nums.size())        //大于size，跳过
continue;
index[nums[i]] = true;
}

for(int i = 0; i < nums.size(); i++){
if(index[i] == false){
cout << i;
return 0;
}
}
cout << nums.size() + 1;
return 0;
}


class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
for(int i = 0; i < nums.size(); i++){
if(nums[i] <= 0)
nums[i] = INT_MAX;
}

for(int i = 0; i < nums.size(); i++){
int number = abs(nums[i]);
if(number <= nums.size())
nums[number - 1] = - abs(nums[number - 1]);
}
for(int i = 0; i < nums.size(); i++){
if(nums[i] > 0)
return i + 1;
}
return nums.size() + 1;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120