洗牌算法详解

洗牌算法详解,第1张

洗牌算法详解 洗牌算法

含义

数组中的数随机打乱,每次打乱后出现的概率应该是均等的。

思路

对于下标 x 而言,我们从 [x,n−1] 中随机出一个位置与 x 进行值交换,当所有位置都进行这样的处理后,我们便得到了一个公平的洗牌方案。

代码实现

int n = nums.length;
Random random = new Random();
for (int i = 0; i < n; i++) {
    //要交换数的下标
    int j = i+random.nextInt(n-i)
    int tem = nums[i];
    nums[i] = nums[j];
    nums[j] =tem;
}
return nums;

例题

  • 题目链接:打乱数组
  • 题目描述
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。

实现 Solution class:

    Solution(int[] nums) 使用整数数组 nums 初始化对象
    int[] reset() 重设数组到它的初始状态并返回
    int[] shuffle() 返回数组随机打乱后的结果
  • 代码实现
class Solution {
    int[] nums;
    public Solution(int[] nums) {
      this.nums = nums;
    }
    public int[] reset() {
      return nums;
    }

    public int[] shuffle() {
        int[] clone = nums.clone();
        int n = nums.length;
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            int j = i+random.nextInt(n-i);
            int tem = clone[i];
            clone[i] = clone[j];
            clone[j] =tem;
        }
        return clone;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5684688.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存