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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容