力扣 (LeetCode)
https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn6gq1/
给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是等可能的。
实现Solution class:
Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果
- 1 <= nums.length <= 50
- -10^6 <= nums[i] <= 10^6
- nums 中的所有元素都是 唯一的
- 最多可以调用 104 次 reset 和 shuffle
从后往前遍历数组,随机生成数组下标,将对应元素放到新数组中,然后将该元素交换至原数组末尾,然后继续循环生成数组下标(此时随机数范围已减一)
public class Solution {
private int[] nums;
private Random random;
public Solution(int[] nums) {
this.nums = nums;
this.random = new Random();
}
public int[] reset() {
return nums;
}
public int[] shuffle() {
if (nums == null) {
return null;
}
int len = nums.length;
int[] clone = nums.clone(); // 涉及数据交换,所以应操作克隆数组
int[] newArray = new int[len];
for (int i = len; i > 0; i--) {
// 在数组中找随机下标数据,放入新数组
int index = random.nextInt(i);
newArray[i - 1] = clone[index];
// 将下标对应数据与末尾数据进行交换
swap(clone, index, i - 1);
}
return newArray;
}
public void swap(int[] a, int i, int j) {
a[i] = a[i] + a[j];
a[j] = a[i] - a[j];
a[i] = a[i] - a[j];
}
}



