forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstMissingPositive.java
More file actions
41 lines (32 loc) · 987 Bytes
/
FirstMissingPositive.java
File metadata and controls
41 lines (32 loc) · 987 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
// First Missing Positive
// URL : https://leetcode.com/problems/first-missing-positive/
package com.akshat;
public class FirstMissingPositive {
public static void main(String[] args) {
int[] nums = {7, 8, 9, 11, 12};
System.out.println(firstMissingPositive(nums));
}
static int firstMissingPositive(int[] nums){
int i = 0;
while (i < nums.length){
int correct = nums[i] - 1;
if (nums[i]>0 && nums[i]<=nums.length && nums[i]!=nums[correct]){
swap(nums, i, correct);
}
else{
i++;
}
}
for (int index=0; index< nums.length; index++){
if (nums[index] != index+1){
return index+1;
}
}
return nums.length+1;
}
static void swap(int[] nums, int first, int second){
int temp = nums[first];
nums[first] = nums[second];
nums[second] = temp;
}
}