384. Shuffle an Array

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
class Solution {
private int[] nums;
private final int[] clonedNums;

public Solution(int[] nums) {
this.nums = nums;
this.clonedNums = nums.clone();
}

public int[] reset() {
nums = clonedNums.clone();
return nums;
}

public int[] shuffle() {
for (int i = 0; i < nums.length; i++) {
int randomIndex = ThreadLocalRandom.current().nextInt(i, nums.length);
swap(nums, i, randomIndex);
}
return nums;
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}

每次从剩余的元素中选择一个,保证了排列数为 n! 个。

References

384. Shuffle an Array