forked from VaibhavD74/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstMissingPositive.java
More file actions
34 lines (31 loc) · 976 Bytes
/
FirstMissingPositive.java
File metadata and controls
34 lines (31 loc) · 976 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
package com.saikat;
import java.util.ArrayList;
import java.util.List;
public class FirstMissingPositive {
public static void main(String[] args) {
int[] nums = {1,2,0};
System.out.println(firstMissingPositive(nums));
}
static int firstMissingPositive(int[] nums) {
int i = 0;
while (i < nums.length){
int correctIndex = nums[i] - 1;
if (nums[i] > 0 && nums[i] <= nums.length && nums[i] != nums[correctIndex]){
swap(nums,i,correctIndex);
}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[] arr, int first, int second){
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}