Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. /**
  2. * Write a function that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. <br/>
  3. * For example, given <code>A = [1, 3, 6, 4, 1, 2]</code>, the function should return 5. <br/>
  4. * Given <code>A = [1, 2, 3]</code>, the function should return 4. <br/>
  5. * Given <code>A = [-1, -3]</code>, the function should return 1. <br/>
  6. * <br/>
  7. * Write an efficient algorithm for the following assumptions: <br/>
  8. * N is an integer within the range <code>[1..100,000]</code>. <br/>
  9. * Each element of array A is an integer within the range <code>[-1,000,000..1,000,000]</code>. <br/>
  10. * <br/>
  11. * Max time for resolution: 30 minutes.
  12. */
  13. class SmallestPositiveIntegerNotOccurring {
  14.  
  15. public static void main(String[] args) {
  16.  
  17. SmallestPositiveIntegerNotOccurring solution = new SmallestPositiveIntegerNotOccurring();
  18.  
  19. System.out.println(solution.solution(new int[] {1, 3, 6, 4, 1, 2})); // 5
  20. System.out.println(solution.solution(new int[] {1, 2, 3})); // 4
  21. System.out.println(solution.solution(new int[] {-1, -3})); // 1
  22. System.out.println(solution.solution(new int[] {-1000000, 1000000})); // 1
  23. }
  24.  
  25. public int solution(int[] A) {
  26.  
  27. // check corner cases
  28. if (A == null || A.length == 0) {
  29. return 1;
  30. }
  31.  
  32. // Each element of array A is an integer within the range [−1,000,000..1,000,000].
  33. // We are going to keep track only of positive numbers we have visited
  34. boolean[] visitedPositives = new boolean[1000000 + 1]; // initialized by the JVM with false
  35.  
  36. // traverse all target array and keep track of positive integers
  37. for (int i=0, c=A.length; i < c; ++i) {
  38.  
  39. // get current number
  40. int current = A[i];
  41.  
  42. // keep track of visited positive numbers
  43. if (current > 0) {
  44. visitedPositives[current] = true;
  45. }
  46. }
  47.  
  48. // traverse visited positive numbers array and keep the index > 0 of the first position marked as false
  49. for (int i=1, c=visitedPositives.length; i < c; i++) {
  50. if (!visitedPositives[i]) {
  51. return i;
  52. }
  53. }
  54.  
  55. // fallback: all positive numbers exist in the A array
  56. return 10000001;
  57. }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement