LeetCode 刷题系列 -- 384. 打乱数组

给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是 等可能 的。

实现 Solution class:

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

示例 1:

输入
["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]
 

提示:

1 <= nums.length <= 50
-106 <= nums[i] <= 106
nums 中的所有元素都是 唯一的
最多可以调用 104 次 reset 和 shuffle

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shuffle-an-array
 

思路:来自于 谈谈游戏中的随机算法 :: labuladong的算法小抄

分析洗牌算法正确性的准则:产生的结果必须有 n! 种可能。这个很好解释,因为一个长度为 n 的数组的全排列就有 n! 种,也就是说打乱结果总共有 n! 种。算法必须能够反映这个事实,才是正确的。

有了这个原则再看代码应该就容易理解了:

对于 nums[0],我们把它随机换到了索引 [0, n) 上,共有 n 种可能性;

对于 nums[1],我们把它随机换到了索引 [1, n) 上,共有 n - 1 种可能性;

对于 nums[2],我们把它随机换到了索引 [2, n) 上,共有 n - 2 种可能性;

以此类推,该算法可以生成 n! 种可能的结果,所以这个算法是正确的,能够保证随机

java代码:

class Solution {
    private int[] nums;
    private Random random = new Random();
    
    public Solution(int[] nums) {
        this.nums = nums;
    }

    public int[] reset() {
        return nums;
    }

    public int[] shuffle() {
        
        int n = nums.length;
        // 复制一份数组到新的空间
        int[] result = Arrays.copyOf(nums, n);

        for (int i = 0; i < n; i++) {
            // 在 i 到 nums.length - 1 中随机找一个位置
            int r = i + random.nextInt(n-i);
            // 交换 i 与 r的顺序
            swap(result,i,r);
        }

        return result;
    }

    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值