2
2
3
3
/**
4
4
*41. First Missing Positive
5
- * Given an unsorted integer array, find the first missing positive integer.
5
+ *Given an unsorted integer array, find the first missing positive integer.
6
6
7
7
For example,
8
8
Given [1,2,0] return 3,
@@ -13,33 +13,35 @@ Your algorithm should run in O(n) time and uses constant space.
13
13
14
14
public class _41 {
15
15
16
- public int firstMissingPositive (int [] nums ) {
17
- int i = 0 ;
18
- while (i < nums .length ) {
19
- if (nums [i ] > 0 && nums [i ] != i + 1
20
- && nums [i ] - 1 < nums .length
21
- && nums [i ] != nums [nums [i ] - 1 ]) {
22
- swap (nums , i , nums [i ] - 1 );
23
- } else {
24
- i ++;
16
+ public static class Solution1 {
17
+ public int firstMissingPositive (int [] nums ) {
18
+ int i = 0 ;
19
+ while (i < nums .length ) {
20
+ if (nums [i ] > 0 && nums [i ] != i + 1
21
+ && nums [i ] - 1 < nums .length
22
+ && nums [i ] != nums [nums [i ] - 1 ]) {
23
+ swap (nums , i , nums [i ] - 1 );
24
+ } else {
25
+ i ++;
26
+ }
25
27
}
26
- }
27
28
28
- for (int j = 0 ; j < nums .length ; j ++) {
29
- if (nums [j ] != j + 1 ) {
30
- return j + 1 ;
29
+ for (int j = 0 ; j < nums .length ; j ++) {
30
+ if (nums [j ] != j + 1 ) {
31
+ return j + 1 ;
32
+ }
31
33
}
32
- }
33
34
34
- return nums .length + 1 ;
35
- /** if all values are in the correct position, then we return the length + 1.
36
- * This also takes care of corner case: [], we return 1 for it.*/
37
- }
35
+ return nums .length + 1 ;
36
+ /** if all values are in the correct position, then we return the length + 1.
37
+ * This also takes care of corner case: [], we return 1 for it.*/
38
+ }
38
39
39
- public void swap (int [] nums , int i , int j ) {
40
- int temp = nums [i ];
41
- nums [i ] = nums [j ];
42
- nums [j ] = temp ;
40
+ public void swap (int [] nums , int i , int j ) {
41
+ int temp = nums [i ];
42
+ nums [i ] = nums [j ];
43
+ nums [j ] = temp ;
44
+ }
43
45
}
44
46
45
47
}
0 commit comments