-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path41_first_missing_positive.java
More file actions
130 lines (102 loc) · 2.93 KB
/
41_first_missing_positive.java
File metadata and controls
130 lines (102 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
*/
/* Solution 01: using array, O(n), O(n) */
class Solution {
public int firstMissingPositive(int[] nums) {
int[] pos_nums = new int[nums.length + 1];
pos_nums[0] = 1;
for (int i = 0;i < nums.length;i ++) {
if (nums[i] > 0 && nums[i] <= nums.length) {
pos_nums[nums[i]] = 1;
}
}
for (int i = 0;i < pos_nums.length;i ++) {
if (pos_nums[i] == 0) {
return i;
}
}
return nums.length + 1;
}
}
/* Solution 02: Sort Array, O(n logn), O(1) */
class Solution {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) {
return 1;
}
Arrays.sort(nums);
int current = 0;
for (int i = 0;i < nums.length;i ++) {
if (nums[i] <= 0) {
continue;
}
if (nums[i] > current + 1) {
return current + 1;
}
current = nums[i];
}
return current + 1;
}
}
/* Solution 03: Hash */
class Solution {
public int firstMissingPositive(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int i = 0;i < nums.length;i ++) {
set.add(nums[i]);
}
for (int i = 1;i <= nums.length;i ++) {
if (! set.contains(i)) {
return i;
}
}
return nums.length + 1;
}
}
/* Solution 04: 2-pointer one pass, O(n), O(1) */
class Solution {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) {
return 1;
}
for (int i = 0;i < nums.length;i ++) {
if (nums[i] <= 0 || nums[i] > nums.length) {
nums[i] = 0;
} else {
if (nums[i] - 1 == i) {
continue;
}
if (nums[i] - 1 > i && nums[nums[i] - 1] != nums[i]) {
swap(nums, i, nums[i] - 1);
i --;
} else {
nums[nums[i] - 1] = nums[i];
nums[i] = 0;
}
}
}
for (int i = 0;i < nums.length;i ++) {
if (nums[i] == 0) {
return i + 1;
}
}
return nums.length + 1;
}
private void swap(int[] nums, int a, int b) {
int temp = nums[b];
nums[b] = nums[a];
nums[a] = temp;
}
}