forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirstMissingPositive.cpp
91 lines (72 loc) · 1.83 KB
/
firstMissingPositive.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Source : https://oj.leetcode.com/problems/first-missing-positive/
// Author : Hao Chen
// Date : 2014-07-18
/**********************************************************************************
*
* 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.
*
*
**********************************************************************************/
#include <iostream>
#include <map>
using namespace std;
#define INT_MAX 2147483647
int firstMissingPositive(int A[], int n) {
map<int, int> cache;
for(int i=0; i<n; i++){
cache[A[i]] = i;
}
//add dummy
if (cache.find(0)==cache.end() ) {
cache[0] = -1;
}
int miss = INT_MAX;
int x;
for (int i=-1; i<n && cache.size()>0; i++){
if (i == -1){
x = 0; //checking dummy
}else{
x = A[i];
}
if ( cache.find(x)==cache.end() ){
continue;
}
int num ;
for( num=x; cache.find(num)!=cache.end(); num--){
cache.erase(cache.find(num));
}
if ( num>0 && num < miss ){
miss = num;
}
for ( num=x+1; cache.find(num)!=cache.end(); num++){
cache.erase(cache.find(num));
}
if ( num>0 && num < miss) {
miss = num;
}
}
return miss;
}
int main()
{
#define TEST(a) cout << firstMissingPositive(a, sizeof(a)/sizeof(int)) << endl
int a1[]={1,2,0};
TEST(a1);
int a2[]={3,4,-1,1};
TEST(a2);
int a3[]={1000,-1};
TEST(a3);
int a4[]={1000, 200};
TEST(a4);
int a5[]={2,5,4,3,-1};
TEST(a5);
int a6[]={1, 100};
TEST(a6);
return 0;
}