yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #384 Shuffle an Array #292

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Solution {
    int[] orgNum;
    int n;
    Random rand;

    public Solution(int[] nums) {
        n = nums.length;
        orgNum = nums;
        rand = new Random();
    }

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

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] arr = orgNum.clone();
        for (int i = 1; i < n; i++) {
            int k = rand.nextInt(i + 1);
            swap(arr, k, i);
        }
        return arr;
    }

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

/**
 * 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();
 */

Random rand = new Random() takes some time to run, instead we can implement Math.random() * size

class Solution {
    int[] orgNum;
    int[] arr;
    int n;

    public Solution(int[] nums) {
        n = nums.length;
        orgNum = nums;
        arr = nums;
    }

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

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int n = arr.length;
        int[] arr = orgNum.clone();
        for (int i = 0; i < n; i++) {
            int rand = (int)(Math.random() * (n - i));
            swap(arr, rand, n - i - 1);
        }
        return arr;
    }

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

/**
 * 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();
 */