Leetcode - Shuffle an Array

My code:

public class Solution {
    private int[] nums;
    private Random r;
    public Solution(int[] nums) {
        this.nums = nums;
        r = new Random(System.currentTimeMillis());
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return this.nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] copy = Arrays.copyOf(nums, nums.length);
        for (int i = 1; i < nums.length; i++) {
            int index = r.nextInt(i + 1);
            int temp = copy[index];
            copy[index] = copy[i];
            copy[i] = temp;
        }
        return copy;
    }
}

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

之前做 find K largest number in array 正好做过类似的。
这道题目不是很好。很难检查。

reference:
https://discuss.leetcode.com/topic/53985/well-explained-o-n-java-solution-by-using-random-class-and-swapping-current-with-a-random-previous-index

Anyway, Good luck, Richardo! — 09/27/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/af3795c35e93#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞