384. Shuffle an Array 发表于 2022-01-16 12345678910111213141516171819202122232425262728class 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! 个。 Reference384. Shuffle an Array