Advertisement
sweet1cris

Untitled

Sep 21st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. public class MissingNumberI {
  2.   // Method 1: use HashSet.
  3.   // Assumption: array is not null.
  4.   public int missingI(int[] array) {
  5.     int n = array.length + 1;
  6.     HashSet<Integer> set = new HashSet<Integer>();
  7.     for (int number : array) {
  8.       set.add(number);
  9.     }
  10.     for (int i = 1; i < n; i++) {
  11.       if (!set.contains(i)) {
  12.         return i;
  13.       }
  14.     }
  15.     return n;
  16.   }
  17.  
  18.   // Method 2: use sum.
  19.   public int missingII(int[] array) {
  20.     int n = array.length + 1;
  21.     long targetSum = (n + 0L) * (n + 1) / 2;
  22.     long actualSum = 0L;
  23.     for (int num : array) {
  24.       actualSum += num;
  25.     }
  26.     return (int) (targetSum - actualSum);
  27.   }
  28.  
  29.   // Method 3: bit operation. - O(n)
  30.   public int missingIII(int[] array) {
  31.     int n = array.length + 1;
  32.     int xor = 0;
  33.     // xor 1 to n.
  34.     for (int i = 1; i <= n; i++) {
  35.       xor ^= i;
  36.     }
  37.     // after this operation, all the numbers from 1 to n
  38.     // are pair xor'ed except for the missing number.
  39.     // since x ^ x = 0, the remaining number is the result.
  40.     for (int num : array) {
  41.       xor ^= num;
  42.     }
  43.     return xor;
  44.   }
  45.  
  46.   // Method 4: swap to the original position. - O(n)
  47.   public int missingIV(int[] array) {
  48.     // try to swap the numbers to its corresponding position.
  49.     // for the number x, the corresponding position is x - 1.
  50.     for (int i = 0; i < array.length; i++) {
  51.       // while array[i] is not i+1, swap array[i] to its correct
  52.       // position if possible.
  53.       while (array[i] != i + 1 && array[i] != array.length + 1) {
  54.         swap(array, i, array[i] - 1);
  55.       }
  56.     }
  57.     // if the missing number is in range of 1 - n-1,
  58.     // then we can find it by checking the index i where array[i] != i+1
  59.     for (int i = 0; i < array.length; i++) {
  60.       if (array[i] != i + 1) {
  61.         return i + 1;
  62.       }
  63.     }
  64.     // if all the numbers of 1 - n-1 are in position,
  65.     // the missing number is n.
  66.     return array.length + 1;
  67.   }
  68.  
  69.   private void swap(int[] array, int i, int j) {
  70.     int tmp = array[i];
  71.     array[i] = array[j];
  72.     array[j] = tmp;
  73.   }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement