-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path384.打乱数组.js
47 lines (41 loc) · 857 Bytes
/
384.打乱数组.js
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
38
39
40
41
42
43
44
45
46
47
/*
* @lc app=leetcode.cn id=384 lang=javascript
*
* [384] 打乱数组
*/
// @lc code=start
/**
* @param {number[]} nums
*/
var Solution = function(nums) {
this.nums = nums;
};
/**
* Resets the array to its original configuration and return it.
* @return {number[]}
*/
Solution.prototype.reset = function() {
return this.nums;
};
/**
* Returns a random shuffling of the array.
* @return {number[]}
*/
Solution.prototype.shuffle = function() {
// Fisher-Yates 洗牌算法
let arr = [...this.nums];
let i = arr.length;
let j = 0;
while (i) {
j = Math.floor(Math.random() * i--);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
};
/**
* 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()
*/
// @lc code=end