Skip to content

Commit cf71eb6

Browse files
committed
Added Java Solution for First_missing_positive
1 parent 2f5f578 commit cf71eb6

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Question : https://leetcode.com/problems/first-missing-positive/
2+
3+
//Example :
4+
/**
5+
* Example 1:
6+
* Input: nums = [1,2,0]
7+
* Output: 3
8+
*
9+
* Example 2:
10+
* nput: nums = [3,4,-1,1]
11+
* Output: 2
12+
*/
13+
14+
// Solution :
15+
16+
import java.*;
17+
import java.util.Scanner;
18+
19+
class Solution {
20+
public static int firstMissingPositive(int[] nums) {
21+
int n = nums.length;
22+
23+
// First of all sort the array using cyclic sort
24+
25+
for(int i = 0; i < n; i++)
26+
while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
27+
int temp1 = nums[i];
28+
int temp2 = nums[nums[i] - 1];
29+
nums[i] = te;
30+
nums[temp1 - 1] = temp1;
31+
}
32+
33+
// Find out first missing positive integer from sorted nums.
34+
35+
for(int j = 0; j < n; j++)
36+
if(nums[j] != j + 1)
37+
return j + 1;
38+
39+
return n + 1;
40+
}
41+
42+
public static void main(String[] args) {
43+
Scanner sc = new Scanner(System.in);
44+
45+
int n = sc.nextInt();
46+
int[] nums = new int[n];
47+
48+
for(int i = 0; i < n ; i ++)
49+
nums[i] = sc.nextInt();
50+
51+
System.out.println(firstMissingPositive(nums));
52+
53+
sc.close();
54+
}
55+
}
56+
57+
// Time complexity : O(n)
58+
// Space complexity : O(1)

0 commit comments

Comments
 (0)