|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
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 |
| - |
15 | 3 | public class _41 {
|
16 | 4 |
|
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; |
31 | 28 | }
|
32 |
| - } |
33 | 29 |
|
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; |
37 | 34 | }
|
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; |
47 | 35 | }
|
48 |
| - } |
49 | 36 | }
|
0 commit comments