File tree Expand file tree Collapse file tree 1 file changed +15
-14
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +15
-14
lines changed Original file line number Diff line number Diff line change @@ -13,32 +13,33 @@ 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 [] A ) {
16
+ public int firstMissingPositive (int [] nums ) {
17
17
int i = 0 ;
18
- while (i < A .length ) {
19
- if (A [i ] > 0 && A [i ] != i + 1
20
- && A [i ] - 1 < A .length
21
- && A [i ] != A [ A [i ] - 1 ]) {
22
- swap (A , i , A [i ] - 1 );
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
23
} else {
24
24
i ++;
25
25
}
26
26
}
27
27
28
- for (int j = 0 ; j < A .length ; j ++) {
29
- if (A [j ] != j + 1 ) {
28
+ for (int j = 0 ; j < nums .length ; j ++) {
29
+ if (nums [j ] != j + 1 ) {
30
30
return j + 1 ;
31
31
}
32
32
}
33
33
34
- return A .length + 1 ;// if all values are in the correct position, then
35
- // we return the last one + 1
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.*/
36
37
}
37
38
38
- public void swap (int [] A , int i , int j ) {// i and j are indices in array A
39
- int temp = A [i ];
40
- A [i ] = A [j ];
41
- A [j ] = temp ;
39
+ public void swap (int [] nums , int i , int j ) {
40
+ int temp = nums [i ];
41
+ nums [i ] = nums [j ];
42
+ nums [j ] = temp ;
42
43
}
43
44
44
45
}
You can’t perform that action at this time.
0 commit comments