File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Leetcode 41. First Missing Positive
2
+ //Question - https://leetcode.com/problems/first-missing-positive/
3
+
4
+ /*Given an unsorted integer array, find the smallest missing positive integer.
5
+
6
+ Example 1:
7
+
8
+ Input: [1,2,0]
9
+ Output: 3
10
+
11
+ Example 2:
12
+
13
+ Input: [3,4,-1,1]
14
+ Output: 2
15
+
16
+ Example 3:
17
+
18
+ Input: [7,8,9,11,12]
19
+ Output: 1
20
+
21
+ Note:
22
+
23
+ Your algorithm should run in O(n) time and uses constant extra space.
24
+ */
25
+
26
+ class Solution {
27
+ public int firstMissingPositive (int [] nums ) {
28
+ if (nums ==null || nums .length ==0 ) return 1 ;
29
+
30
+ boolean oneFound = false ;
31
+ for (int i =0 ;i <nums .length ;i ++){
32
+ if (nums [i ]==1 ) oneFound = true ;
33
+ else if (nums [i ]<=0 ) nums [i ] = Integer .MAX_VALUE ;
34
+ }
35
+
36
+ if (!oneFound ) return 1 ;
37
+
38
+ for (int i =0 ; i <nums .length ; i ++){
39
+ int targetIndex = Math .abs (nums [i ])-1 ;
40
+ if (targetIndex >=0 && targetIndex <nums .length ){
41
+ nums [targetIndex ] = Math .abs (nums [targetIndex ])*-1 ;
42
+ }
43
+ }
44
+
45
+ for (int i =0 ;i <nums .length ;i ++){
46
+ if (nums [i ]>0 ) return (i +1 );
47
+ }
48
+ return nums .length +1 ;
49
+
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments