forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
First_Missing_Positive.cpp
56 lines (46 loc) · 1.09 KB
/
First_Missing_Positive.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: June 28, 2012
Problem: First Missing Positive
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Solution:
Two traverses.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
class Solution {
public:
int firstMissingPositive(int A[], int n) {
bool arr[n + 2];
int result = 1;
for (int i = 1; i < n + 2; i++) {
arr[i] = false;
}
for (int i = 0; i < n; i++) {
if (A[i] > 0 && A[i] < n + 1) {
arr[A[i]] = true;
}
}
for (int i = 1; i < n + 2; i++) {
if (!arr[i]) {
result = i;
break;
}
}
return result;
}
};