that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer (greater than 0) that does not occur in A. For example, given:
A[0] = 4
A[1] = 6
A[2] = 2
A[3] = 2
A[4] = 6
A[5] = 6
A[6] = 1
the function should return 4. Assume that:
in other words, A[K] = 2 for each K (0 <= K <= 50000), the given implementation works too slow, but the function would return 50,000
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1...100,000]
each element of array A is an integer the range [1..N]
My Answer is not yet successful! What is wrong with it? First let me state the obvious errors
- return value - I return 4 in the first result and that was successful but the second return is 1 that is not correct for the reason that the expected result is 50,000
my code, which works but the only first result is correct and second is not.
import java.util.*;
class Solution {
int solution(int[] A) {
int[] AN = Arrays.stream(A).filter(n -> n > 0).distinct().sorted().toArray();
int N = AN.length;
int min = 1;
int i = 0;
while (i < N) {
min = i+1;
if (min == N) {
min = Math.max(min , Math.abs(i-N));
}
i++;
}
return min;
}
}