-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstMissingPositive.java
More file actions
39 lines (37 loc) · 1.17 KB
/
FirstMissingPositive.java
File metadata and controls
39 lines (37 loc) · 1.17 KB
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
/*
* https://leetcode.com/problems/first-missing-positive/
*/
public class FirstMissingPositive {
public int firstMissingPositive(int[] nums) {
if (nums.length == 0) {
return 1;
}
boolean lengthElementPresent = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
nums[i] = -1;
} else if (nums[i] == nums.length) {
lengthElementPresent = true;
}
}
for (int i = 0; i < nums.length; i++) {
checkIndexAndSetZero(nums, nums[i]);
}
for (int i = 1; i < nums.length; i++) {
if (nums[i] != 0) {
return i;
}
}
return lengthElementPresent ? nums.length + 1 : nums.length;
}
private void checkIndexAndSetZero(int[] nums, int value) {
if (value > 0 && value < nums.length) {
int temp = nums[value];
nums[value] = 0;
checkIndexAndSetZero(nums, temp);
}
}
public static void main(String[] args) {
System.out.println(new FirstMissingPositive().firstMissingPositive(new int[]{3, 4, -1, 1})); // 2
}
}