Problem 384

Posted by Ruizhi Ma on October 29, 2020

Solution URL

https://leetcode.com/submissions/detail/414663708/

代码

class Solution {

    private int[] arr;
    private int[] original;

    Random rand = new Random();

    public Solution(int[] nums) {
        arr = nums;
        original = nums.clone();
    }

    public int random(int min, int max){
        return rand.nextInt(max - min) + min;
    }

    public void swap(int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        arr = original;
        original = original.clone();
        return original;
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        for(int i = 0; i < arr.length; i++){
            swap(i, random(i, arr.length));
        }

        return arr;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int[] param_1 = obj.reset();
 * int[] param_2 = obj.shuffle();
 */