leetcode-384. 打乱数组

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
分析

使用两个全局数组存储变量,一个用于reset保持初始状态,另一个用于shuffle存储随机后的结果。

对于reset,直接返回原始save即可

对于shuffle,遍历数组,每次从[i:]选择一个元素放置在i的位置上。从概率上来讲每个元素在每个位置上的概率是一样的

代码
public int[] save;
public int[] running;
public Solution(int[] nums) {
    save = new int[nums.length];
    for(int i=0;i<nums.length;i++) save[i] = nums[i];
    running = nums;
    // List<Integer> temp = new ArrayList<>();
    // Arrays.stream(nums).forEach(x->temp.add(x));
}

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

public int[] shuffle() {
    int length = running.length-1;
    for(int i=0;i<running.length;i++){
        int randInd = (int)(i+Math.random()*(length-i+1));
        int temp = running[randInd];
        running[randInd] = running[i];
        running[i] = temp;
    }
    return running;
}
结果

时间超过65.04%

内存超过99.58%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值