-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFirstMissingInteger.java
More file actions
44 lines (36 loc) · 878 Bytes
/
FirstMissingInteger.java
File metadata and controls
44 lines (36 loc) · 878 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
35
36
37
38
39
40
41
42
43
44
package arrays;
import java.util.Arrays;
/**
* Given an unsorted integer array, find the first missing positive integer.
* Example:
* Given [1,2,0] return 3,
* [3,4,-1,1] return 2,
* [-8, -7, -6] returns 1
* Your algorithm should run in O(n) time and use constant space.
*/
public class FirstMissingInteger {
// Driver method
public static void main (String[] args)
{
// your code goes here
int arr[] = {3,4,-1,1};
int result = firstMissingPositive(arr);
System.out.println(result);
}
static int firstMissingPositive(int[] A)
{
Arrays.sort(A);
int m=1;
for(int i=0;i<A.length;i++)
{
if(A[i]>0)
{
if(m==A[i])
m++;
else
return m;
}
}
return m;
}
}