384. 打乱数组
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是 等可能 的。
实现 Solution class:
- Solution(int[] nums) 使用整数数组 nums 初始化对象
- int[] reset() 重设数组到它的初始状态并返回
- int[] shuffle() 返回数组随机打乱后的结果
解:
- 洗牌算法,每个数等概率出现在任一位置
- 遍历数组,i 的范围是 [0, n -1]。从 [i, n - 1]范围上等概率取一个随机数rand,把rand上的数和i位置上的数互换
class Solution {
private nums: number[]
private oNums: number[]
constructor(nums: number[]) {
this.nums = nums
this.oNums = [...nums]
}
reset(): number[] {
this.nums = [...this.oNums]
return this.nums
}
shuffle(): number[] {
for (let i = 0; i < this.nums.length; i++) {
const rand = ~~(Math.random() * (this.nums.length - i)) + i;
[this.nums[i], this.nums[rand]] = [this.nums[rand], this.nums[i]]
}
return this.nums
}
}