File tree Expand file tree Collapse file tree 1 file changed +6
-2
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +6
-2
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
3
/**
4
+ *41. First Missing Positive
4
5
* Given an unsorted integer array, find the first missing positive integer.
5
6
6
7
For example,
7
8
Given [1,2,0] return 3,
8
9
and [3,4,-1,1] return 2.
9
10
10
11
Your algorithm should run in O(n) time and uses constant space.
11
-
12
12
*/
13
+
13
14
public class _41 {
14
15
15
16
public int firstMissingPositive (int [] A ) {
16
17
int i = 0 ;
17
18
while (i < A .length ) {
18
- if (A [i ] > 0 && A [i ] != i + 1 && A [i ] - 1 < A .length
19
+ if (A [i ] > 0 && A [i ] != i + 1
20
+ && A [i ] - 1 < A .length
19
21
&& A [i ] != A [A [i ] - 1 ]) {
20
22
swap (A , i , A [i ] - 1 );
21
23
} else {
22
24
i ++;
23
25
}
24
26
}
27
+
25
28
for (int j = 0 ; j < A .length ; j ++) {
26
29
if (A [j ] != j + 1 ) {
27
30
return j + 1 ;
28
31
}
29
32
}
33
+
30
34
return A .length + 1 ;// if all values are in the correct position, then
31
35
// we return the last one + 1
32
36
}
You can’t perform that action at this time.
0 commit comments