[LeetCode] 384 - Shuffle an Array

LeetCode Problem Link: https://leetcode.com/problems/shuffle-an-array/description/

Solution:
class Solution {
    
    private int[] mNums = null;
    private Random mRandom;
    

    public Solution(int[] nums) {
        mNums = nums;
        mRandom = new Random();
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return mNums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] shuffle = mNums.clone();
        for (int i = mNums.length - 1; i > 0; i--) {
            int shuffle_idx = mRandom.nextInt(i + 1);
            swap(shuffle, i, shuffle_idx);
        }
        return shuffle;
    }
    
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

Remark:
1. Math.random() consumes more time than Random.nextInt()
2. For loop stops at i > 0 also save some runtime.

Result:
Around 260ms
Beats about 50% users

留言