打乱数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @param {number[]} nums
*/
var Solution = function (nums) {
this.nums = nums;
this.bankNums = [...this.nums];
};

/**
* @return {number[]}
*/
Solution.prototype.reset = function () {
this.nums = [...this.bankNums];
return this.nums;
};

/**
* @return {number[]}
*/
Solution.prototype.shuffle = function () {
// 洗牌算法
const nums = [...this.nums];
for (let i = 0; i < nums.length; i++) {
const j = Math.floor(Math.random() * nums.length);
const temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
return nums;
};

/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/

注意Math.random()返回的是[0,1)左闭右开,所以j=Math.floor(Math.random() * (nums.length - 1))他的取值范围是[0, nums.length-2]最后一个元素不会打乱,所以不公平


本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。