Skip to content

Commit 64f09fa

Browse files
author
Sherali Obidov
committed
first missing positive
1 parent ff2bede commit 64f09fa

3 files changed

Lines changed: 48 additions & 2 deletions

File tree

‎src/problems/Hard.txt‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,13 @@ Note:
195195

196196
sx, sy, tx, ty will all be integers in the range [1, 10^9].
197197

198+
14) First Missing Positive
199+
Given an unsorted integer array, find the first missing positive integer.
200+
201+
For example,
202+
Given [1,2,0] return 3,
203+
and [3,4,-1,1] return 2.
204+
205+
Your algorithm should run in O(n) time and uses constant space.
206+
207+
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package problems.hard;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Why Did you create this class? what does it do?
7+
*/
8+
public class FirstMissingPositive {
9+
10+
public int firstMissingPositive(int[] a) {
11+
if (a == null || a.length == 0)
12+
return 1;
13+
for (int i = 0; i < a.length; i++) {
14+
if (a[i] <= 0 || a[i] > a.length) {
15+
a[i] = 0;
16+
}
17+
}
18+
19+
for (int i = 0; i < a.length; i++) {
20+
if (a[i] == 0)
21+
continue;
22+
int index = Math.abs(a[i]) - 1;
23+
if (a[index] == 0)
24+
a[index] = -1 * Math.abs(a[i]);
25+
else
26+
a[index] = -1 * Math.abs(a[index]);
27+
}
28+
System.out.println(Arrays.toString(a));
29+
int i = 0;
30+
for (; i < a.length; i++) {
31+
if (a[i] >= 0)
32+
return i + 1;
33+
}
34+
35+
return i + 1;
36+
}
37+
}

‎src/problems/medium/ArrayNesting.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@
66
public class ArrayNesting {
77

88
public int arrayNesting(int[] nums) {
9-
if (nums == null || nums.length == 0) {
9+
if (nums == null || nums.length == 0)
1010
return 0;
11-
}
1211

1312
boolean[] a = new boolean[nums.length];
1413
int max = 0;

0 commit comments

Comments
 (0)