-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
42 lines (38 loc) · 1.21 KB
/
Copy pathSolution.java
File metadata and controls
42 lines (38 loc) · 1.21 KB
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
/**
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A.
For example, given:
A[0] = 1
A[1] = 3
A[2] = 6
A[3] = 4
A[4] = 1
A[5] = 2
the function should return 5.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
import java.util.HashSet;
public class Solution {
public static int solution(int[] array) {
int num = 1;
HashSet<Integer> hashSet = new HashSet<Integer>();
for (int i = 0 ; i < array.length; i++) {
hashSet.add(array[i]);
while (hashSet.contains(num)) {
num++;
}
}
return num;
}
public static void main(String[] args){
int[] array = {1,2,-1,6,7,8};
System.out.println(solution(array));
}
}