384.打乱数组

给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。

实现 Solution class:

Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果
 

示例:

输入
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
输出
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

解释
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2]
solution.reset(); // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]
solution.shuffle(); // 随机返回数组 [1, 2, 3] 打乱后的结果。例如,返回 [1, 3, 2]

思路:

  • 随机算法之 — "洗牌算法" 。
  • 保存一份原始样本,需要返回初始状态时,直接返回原始样本;
  • 随机打乱数组,随机获取在当前下标后面的下标,为什么是后面而不是全局的随机下标,其实是一样的;
  • 利用 Random 来获得随机的下标,将当前下标与随机下标进行交换。

class Solution {
    private int[] original; //记录原始样本值

    public Solution(int[] nums) {
        original = nums.clone();
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return original; //返回原始样本
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] array = original.clone(); //拷贝一份副本,对副本进行修改
        for(int i = 0; i < array.length; i++){
            int idx = randomInt(i, array.length); //得到随机坐标
            int tmp = array[i]; // 交换数组下标的值
            array[i] = array[idx];
            array[idx] = tmp;
        }
        return array;
    }

    Random random = new Random(); //产生随机坐标
    private int randomInt(int start, int end){
        return random.nextInt(end - start) + start; //产生一个[start, end) 的随机数
    }
}
原文地址:https://www.cnblogs.com/luo-c/p/13928765.html