Skip to content

Commit 3c070b8

Browse files
[N-0] refactor 41
1 parent 0e8fd3b commit 3c070b8

File tree

1 file changed

+25
-23
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+25
-23
lines changed

src/main/java/com/fishercoder/solutions/_41.java

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
/**
44
*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.
66
77
For example,
88
Given [1,2,0] return 3,
@@ -13,33 +13,35 @@ Your algorithm should run in O(n) time and uses constant space.
1313

1414
public class _41 {
1515

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+
}
2527
}
26-
}
2728

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+
}
3133
}
32-
}
3334

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+
}
3839

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+
}
4345
}
4446

4547
}

0 commit comments

Comments
 (0)