- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathFirstMissingPositive41.java
More file actions
Latest commit
134 lines (104 loc) · 3.12 KB
/
Copy pathFirstMissingPositive41.java
File metadata and controls
134 lines (104 loc) · 3.12 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/**
* 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.
*/
importjava.util.ArrayList;
importjava.util.List;
publicclassFirstMissingPositive41 {
publicintfirstMissingPositive(int[] nums) {
List<Boolean> isMissing = newArrayList<>();
isMissing.add(false);
intfirstMissing = 1;
for (inti = 0; i < nums.length; i++) {
intnow = nums[i];
if (now > 0) {
try {
if (isMissing.get(now)) {
isMissing.set(now, false);
}
} catch (IndexOutOfBoundsExceptione) {
while (isMissing.size() < now) {
isMissing.add(true);
}
isMissing.add(false);
}
}
try {
while (!isMissing.get(firstMissing)) {
firstMissing++;
}
} catch (IndexOutOfBoundsExceptione) {
isMissing.add(true);
}
}
returnfirstMissing;
}
/**
*
*/
publicintfirstMissingPositive2(int[] nums) {
if (nums == null || nums.length == 0) {
return1;
}
for (inti = 0; i < nums.length; ++i) {
while (nums[i] > 0 && nums[i] <= nums.length && nums[i] - 1 != i) {
inttmp = nums[nums[i] - 1];
if (tmp == nums[i]) {
break;
}
nums[nums[i] - 1] = nums[i];
nums[i] = tmp;
}
}
for (inti = 0; i < nums.length; ++i) {
if (nums[i] != i + 1) {
returni + 1;
}
}
returnnums.length + 1;
}
/**
* https://leetcode.com/problems/first-missing-positive/discuss/17083/O(1)-space-Java-Solution
*/
publicintfirstMissingPositive3(int[] A) {
inti = 0;
while(i < A.length){
if(A[i] == i+1 || A[i] <= 0 || A[i] > A.length) i++;
elseif (A[A[i]-1] != A[i]) swap(A, i, A[i]-1);
elsei++;
}
i = 0;
while(i < A.length && A[i] == i+1) i++;
returni+1;
}
privatevoidswap(int[] A, inti, intj){
inttemp = A[i];
A[i] = A[j];
A[j] = temp;
}
publicintfirstMissingPositive4(int[] nums) {
if (nums == null || nums.length == 0) return1;
intN = nums.length;
for (inti=0; i<N; i++) {
intidx = i;
intval = nums[idx];
while (idx >= 0 && idx < N && val > 0 && val <= N && nums[idx] != idx + 1) {
intnewVal = nums[val - 1];
nums[val - 1] = val;
idx = newVal - 1;
val = newVal;
}
}
for (inti=0; i<N; i++) {
if (nums[i] != i + 1) {
returni + 1;
}
}
returnN + 1;
}
}