File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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)
You can’t perform that action at this time.
0 commit comments