-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstMissingPositive.java
More file actions
29 lines (29 loc) · 884 Bytes
/
FirstMissingPositive.java
File metadata and controls
29 lines (29 loc) · 884 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
class Solution {
public int firstMissingPositive(int[] nums) {
int minPositive = Integer.MAX_VALUE;
int n = nums.length, i;
for(i = 0; i < n; i++) {
if(nums[i] < minPositive && nums[i] > 0)
minPositive = nums[i];
}
if(minPositive != 1) return 1;
for(i = 0; i < n; i++) {
if(nums[i] < 1 || nums[i] > n)
nums[i] = 1;
}
for(i = 0; i < n; i++) {
int current = Math.abs(nums[i]);
if(current == n)
nums[0] = -1 * Math.abs(nums[0]);
else
nums[current] = -1 * Math.abs(nums[current]);
}
for(i = 0; i < n; i++) {
int current = nums[i];
if(current > 0 && i > 0)
return i;
}
if(nums[0] > 0) return n;
return n + 1;
}
}