Skip to content

Commit 1ee1bb1

Browse files
refactor 41
1 parent 6e4b7ed commit 1ee1bb1

File tree

1 file changed

+27
-40
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+27
-40
lines changed
Lines changed: 27 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,36 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
*41. First Missing Positive
5-
*
6-
*Given an unsorted integer array, find the first missing positive integer.
7-
8-
For example,
9-
Given [1,2,0] return 3,
10-
and [3,4,-1,1] return 2.
11-
12-
Your algorithm should run in O(n) time and uses constant space.
13-
*/
14-
153
public class _41 {
164

17-
public static class Solution1 {
18-
/**
19-
* Time: O(n) Space: O(1)
20-
*
21-
* Idea: put every number in its right position, e.g. put 5 in nums[4].
22-
*/
23-
public int firstMissingPositive(int[] nums) {
24-
int i = 0;
25-
while (i < nums.length) {
26-
if (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.length && nums[i] != nums[nums[i]
27-
- 1]) {
28-
swap(nums, i, nums[i] - 1);
29-
} else {
30-
i++;
5+
public static class Solution1 {
6+
/**
7+
* Time: O(n) Space: O(1)
8+
* Idea: put every number in its right position, e.g. put 5 in nums[4].
9+
*/
10+
public int firstMissingPositive(int[] nums) {
11+
int i = 0;
12+
while (i < nums.length) {
13+
if (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.length && nums[i] != nums[nums[i]
14+
- 1]) {
15+
swap(nums, i, nums[i] - 1);
16+
} else {
17+
i++;
18+
}
19+
}
20+
21+
for (int j = 0; j < nums.length; j++) {
22+
if (nums[j] != j + 1) {
23+
return j + 1;
24+
}
25+
}
26+
27+
return nums.length + 1;
3128
}
32-
}
3329

34-
for (int j = 0; j < nums.length; j++) {
35-
if (nums[j] != j + 1) {
36-
return j + 1;
30+
void swap(int[] nums, int i, int j) {
31+
int temp = nums[i];
32+
nums[i] = nums[j];
33+
nums[j] = temp;
3734
}
38-
}
39-
40-
return nums.length + 1;
41-
}
42-
43-
void swap(int[] nums, int i, int j) {
44-
int temp = nums[i];
45-
nums[i] = nums[j];
46-
nums[j] = temp;
4735
}
48-
}
4936
}

0 commit comments

Comments
 (0)