384. Shuffle an Array

Link

Solution

熟悉Random用法 random.nextInt(n); // 產生 0~(n-1)的隨機數

Swap 任意兩index造成隨機

int[] nums;
    Random random;
    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }
    
    /** 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();
        for(int i = 0; i < a.length; i++){
            int j = random.nextInt(a.length);
            swap(a, i , j);
        }
        return a;
    }
    
    public void swap(int[] a, int i, int j){
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

Last updated

Was this helpful?