• 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) 的随机数
        }
    }
  • 相关阅读:
    Maya 与 Matlab 数据互联插件使用教程
    代码可视化算法流程
    sql 至少含有
    sql update limit1
    c# windows service 程序
    c#和.net区别
    c#数据库乱码
    c#事件实质
    c#非界面线程控制控件
    mysql唯一查询
  • 原文地址:https://www.cnblogs.com/luo-c/p/13928765.html
Copyright © 2020-2023  润新知