forked from mengli/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstMissingPositive.java
More file actions
Latest commit
32 lines (28 loc) · 667 Bytes
/
Copy pathFirstMissingPositive.java
File metadata and controls
32 lines (28 loc) · 667 Bytes
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
/**
* Given an unsorted integer array, find the first missing positive integer.
*
* For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2.
*
* Your algorithm should run in O(n) time and uses constant space.
*/
publicclassFirstMissingPositive {
publicintfirstMissingPositive(int[] A) {
if (A.length == 0)
return1;
for (inti = 0; i < A.length; i++) {
if (A[i] > 0 && A[i] - 1 < A.length && A[i] - 1 != i
&& A[i] != A[A[i] - 1]) {
intt = A[A[i] - 1];
A[A[i] - 1] = A[i];
A[i] = t;
i--;
}
}
for (intj = 0; j < A.length; j++) {
if (A[j] - 1 != j) {
returnj + 1;
}
}
returnA.length + 1;
}
}