Task Score :100
Correctness :100
Performance : 100
Task description
This is a demo task.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
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 within the range [−1,000,000..1,000,000].
Solution
import java.util.Arrays;
public class MissingInteger {
public static void main(String[] args) {
int[] A = { 1, 3, 6, 4, 1, 2 };
System.out.println(new MissingInteger().solution(A));
}
public int solution(int[] A) {
Arrays.sort(A);
if (A.length == 0) {
return 1;
}
if (A.length == 1 && A[0] != 1) {
return 1;
}
if (A[A.length - 1] < 1) {
return 1;
}
int[] t = new int[A[A.length - 1] + 1]; //Temp array to mark occurences
for (int i : A) {
if (i < 1) {
continue;
}
t[i] = t[i] + 1;
}
for (int i = 0; i < t.length; i++) {
if (i > 0 && t[i] == 0) {
return i;
}
}
return A[A.length - 1] + 1;
}
}
No comments:
Post a Comment