-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path384.打乱数组.js
45 lines (41 loc) · 892 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
/*
* @lc app=leetcode.cn id=384 lang=javascript
*
* [384] 打乱数组
*/
// @lc code=start
/**
* @param {number[]} nums
*/
var Solution = function (nums) {
this.nums = nums;
this.original = [...nums];
};
/**
* @return {number[]}
*/
Solution.prototype.reset = function () {
this.nums = [...this.original];
return this.nums;
};
/**
* @return {number[]}
*/
Solution.prototype.shuffle = function () {
function swap(arr, i, j) {
const c = arr[j];
(arr[j] = arr[i]), (arr[i] = c);
}
for (let i = 0; i < this.nums.length; i++) {
const j = i + Math.floor(Math.random() * (this.nums.length - i));
swap(this.nums, i, j);
}
return this.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()
*/
// @lc code=end