Advertisement
1988coder

384. Shuffle an Array

Jan 27th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/shuffle-an-array/
  3. import java.util.Random;
  4.  
  5. /**
  6.  * Fisher-Yates Algorithm
  7.  *
  8.  * Refer: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
  9.  *
  10.  * In Shuffle function, probability of each item in array is equal (1 / N). This
  11.  * is due to reservoir sampling with size of reservoir as 1.
  12.  *
  13.  * Suppose the indexes of the array are from 1 to N. You have already placed i-1
  14.  * elements. Now you are trying to place ith element. The probability to place
  15.  * it at an index between 1 & i is 1/i. Now you do not want to replace ith
  16.  * number by any future numbers.. Thus, the final probability for ith element =
  17.  * 1/i * (1 - 1/(i+1)) * (1 - 1/(i+2)) * .. * (1 - 1/N) = 1 / N.
  18.  *
  19.  * Time Complexity: 1) Solution() -> O(N).. 2) reset() -> O(N).. 3) shuffle() ->
  20.  * O(N)
  21.  *
  22.  * Space Complexity: O(N). This is required for clone of original array.
  23.  *
  24.  * N = length of the input array.
  25.  */
  26. class Solution {
  27.  
  28.     int[] origArr;
  29.     int[] numsArr;
  30.     Random rand;
  31.  
  32.     public Solution(int[] nums) {
  33.         if (nums == null) {
  34.             return;
  35.         }
  36.         numsArr = nums;
  37.         origArr = nums.clone();
  38.         rand = new Random();
  39.     }
  40.  
  41.     /** Resets the array to its original configuration and return it. */
  42.     public int[] reset() {
  43.         if (origArr == null) {
  44.             return null;
  45.         }
  46.         numsArr = origArr.clone();
  47.         return numsArr;
  48.     }
  49.  
  50.     /** Returns a random shuffling of the array. */
  51.     public int[] shuffle() {
  52.         if (numsArr == null || numsArr.length <= 1) {
  53.             return numsArr;
  54.         }
  55.  
  56.         for (int i = 1; i < numsArr.length; i++) {
  57.             int idx = rand.nextInt(i + 1);
  58.             if (idx != i) {
  59.                 int temp = numsArr[i];
  60.                 numsArr[i] = numsArr[idx];
  61.                 numsArr[idx] = temp;
  62.             }
  63.         }
  64.  
  65.         return numsArr;
  66.     }
  67. }
  68.  
  69. /**
  70.  * Your Solution object will be instantiated and called as such: Solution obj =
  71.  * new Solution(nums); int[] param_1 = obj.reset(); int[] param_2 =
  72.  * obj.shuffle();
  73.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement