Skip to content

Instantly share code, notes, and snippets.

@TheDIM47
Last active October 27, 2015 10:10
Show Gist options
  • Save TheDIM47/0a5263e6aaffe9daeaba to your computer and use it in GitHub Desktop.
Save TheDIM47/0a5263e6aaffe9daeaba to your computer and use it in GitHub Desktop.
Find missing Integer in array with Java
public class MissingElement {
public int solution(int[] A) {
if (A == null) return 1;
else if (A.length == 0) return 1;
else {
java.util.Arrays.sort(A);
return evaluate(A, 0, A.length - 1);
}
}
int evaluate(int[] A, int start, int stop) {
int mid = (stop + start) / 2;
int expected = A[0] + mid;
if (start == stop) {
if (A[start] == (A[0] + start))
if (A[0] == 1)
return A[0] + A.length;
else
return 1;
else
return (A[0] + start);
} else
if (A[mid] > expected)
return evaluate(A, start, mid);
else
return evaluate(A, mid+1, stop);
}
public static void main(String[] args) {
assert(new MissingElement().solution(new int[] { 1 })) == 2;
assert(new MissingElement().solution(new int[] { 2 })) == 1;
assert(new MissingElement().solution(new int[] { 1, 2 })) == 3;
assert(new MissingElement().solution(new int[] { 2, 3 })) == 1;
assert(new MissingElement().solution(new int[] { 3, 5 })) == 4;
assert(new MissingElement().solution(new int[] { 2, 3, 5 })) == 4;
assert(new MissingElement().solution(new int[] { 1, 2, 3, 5 })) == 4;
assert(new MissingElement().solution(new int[] { 0, 1, 2, 3, 5 })) == 4;
assert(new MissingElement().solution(new int[] { 0, 1, 2, 3, 5, 6 })) == 4;
assert(new MissingElement().solution(new int[] { 11, 13 })) == 12;
assert(new MissingElement().solution(new int[] { 11, 12, 14 })) == 13;
assert(new MissingElement().solution(new int[] { 11, 13, 14, 15, 16 })) == 12;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment