-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathFirst Missing Positive.java
58 lines (43 loc) · 1.26 KB
/
First Missing Positive.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Question : https://leetcode.com/problems/first-missing-positive/
//Example :
/**
* Example 1:
* Input: nums = [1,2,0]
* Output: 3
*
* Example 2:
* nput: nums = [3,4,-1,1]
* Output: 2
*/
// Solution :
import java.*;
import java.util.Scanner;
class Solution {
public static int firstMissingPositive(int[] nums) {
int n = nums.length;
// First of all sort the array using cyclic sort
for(int i = 0; i < n; i++)
while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
int temp1 = nums[i];
int temp2 = nums[nums[i] - 1];
nums[i] = temp2;
nums[temp1 - 1] = temp1;
}
// Find out first missing positive integer from sorted nums.
for(int j = 0; j < n; j++)
if(nums[j] != j + 1)
return j + 1;
return n + 1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n ; i ++)
nums[i] = sc.nextInt();
System.out.println(firstMissingPositive(nums));
sc.close();
}
}
// Time complexity : O(n)
// Space complexity : O(1)