-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSolution.java
More file actions
46 lines (42 loc) · 982 Bytes
/
Solution.java
File metadata and controls
46 lines (42 loc) · 982 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package FirstMissingPositive;
/**
* User: Danyang
* Date: 1/19/2015
* Time: 11:21
* 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.
*/
public class Solution {
/**
* Without additional space
* 0 does not count
*
* Notice:
* 1. duplicate
*
* Test cases:
* 0. []
* 1. [1, 1]
* @param A
* @return
*/
public int firstMissingPositive(int[] A) {
for(int i=0; i<A.length; ) {
int pos = A[i] - 1;
if(pos>=0 && pos<A.length && i!=pos && A[pos]!=pos+1) {
int t = A[i]; A[i] = A[pos]; A[pos] = t;
}
else {
i++;
}
}
for(int i=0; i<A.length; i++) {
if(A[i]!=i+1)
return i+1;
}
return A.length+1;
}
}