给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是 等可能 的。
实现 Solution class:
Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果
class Solution {
int[] num;
int len;
Random random = new Random();
public Solution(int[] nums) {
this.num = nums;
this.len = nums.length;
}
public int[] reset() {
return this.num;
}
public int[] shuffle() {
int[] clone = num.clone();
for(int i = 0;i < len;i++){
swap(clone,i,i+random.nextInt(len-i));
}
return clone;
}
public void swap(int[] nums,int i ,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/
执行用时:49 ms, 在所有 Java 提交中击败了96.23%的用户
内存消耗:47.3 MB, 在所有 Java 提交中击败了86.73%的用户