Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
63 lines (53 loc) · 1.6 KB

File metadata and controls

63 lines (53 loc) · 1.6 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package Algorithms.array;
public class FirstMissingPositive {
public static void main(String[] strs) {
int[] in = {1,4,2,3};
//int[] in = {3,4,-1,1};
System.out.println(firstMissingPositive(in));
}
public static int firstMissingPositive1(int[] A) {
if (A == null) {
return 0;
}
int len = A.length;
for (int i = 0; i < len; i++) {
// 1. The number should be in the range.
// 2. The number should be positive.
while (A[i] <= len && A[i] > 0 && A[A[i] - 1] != A[i]) {
swap(A, i, A[i] - 1);
}
}
for (int i = 0; i < len; i++) {
if (A[i] != i + 1) {
return i + 1;
}
}
return len + 1;
}
public static void swap(int[] A, int i, int j) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
// SOLUTION 2:
public static int firstMissingPositive(int[] A) {
// bug 3: when length is 0, return 1;
if (A == null) {
return 0;
}
for (int i = 0; i < A.length; i++) {
// 1: A[i] is in the range;
// 2: A[i] > 0.
// 3: The target is different;
while (A[i] <= A.length && A[i] > 0 && A[A[i] - 1] != A[i]) {
swap(A, i, A[i] - 1);
}
}
for (int i = 0; i < A.length; i++) {
if (A[i] != i + 1) {
return i + 1;
}
}
return A.length + 1;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.