Java Solution


  • 0
    C

    Time O(N), Space O(N)
    the Algorithm is :
    [0, 1, 2, ... N-1]

    randomly pick one of them and swap to the index 0 position.
    [X, 1, 2, ... N-1]

    then pick one of them form {1: N-1} and swap to index 1 position.
    etc...

    import java.util.Random;
    public class Solution {
        private Random rand;
        private int[] nums;
        
        public Solution(int[] nums) {
            rand = new Random();
            this.nums = nums;
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return nums;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            int[] a = nums.clone();
            int len = a.length;
            for(int i=0; i<len; i++) {
                int r = i + rand.nextInt(len-i);
                int t = a[i]; a[i] = a[r]; a[r] = t;
            }
            return a;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.