Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e3603ed

Browse files
refactor 41
1 parent 6759a4b commit e3603ed

File tree

1 file changed

+15
-14
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+15
-14
lines changed

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

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,32 +13,33 @@ Your algorithm should run in O(n) time and uses constant space.
1313

1414
public class _41 {
1515

16-
public int firstMissingPositive(int[] A) {
16+
public int firstMissingPositive(int[] nums) {
1717
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);
2323
} else {
2424
i++;
2525
}
2626
}
2727

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) {
3030
return j + 1;
3131
}
3232
}
3333

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.*/
3637
}
3738

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;
4243
}
4344

4445
}

0 commit comments

Comments
 (0)