给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是 等可能 的。
实现 Solution class:
Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果
示例 1:
输入
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
输出
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
解释
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2]
solution.reset(); // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]
solution.shuffle(); // 随机返回数组 [1, 2, 3] 打乱后的结果。例如,返回 [1, 3, 2]
提示:
1 <= nums.length <= 50
-106 <= nums[i] <= 106
nums 中的所有元素都是 唯一的
最多可以调用 104 次 reset 和 shuffle
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shuffle-an-array
(1)洗牌算法
有关洗牌算法可以参考洗牌算法详解:你会排序,但你会打乱吗?这篇文章。
//思路1————洗牌算法
class Solution {
//当前数组
int[] nums;
//初始数组
int[] oriNums;
public Solution(int[] nums) {
this.nums = nums;
this.oriNums = new int[nums.length];
//将 nums 中的元素复制到 oriNums 中
System.arraycopy(nums, 0, oriNums, 0, nums.length);
}
public int[] reset() {
//将 oriNums 中的元素复制到 nums 中,即完成回到初始化状态
System.arraycopy(oriNums, 0, nums, 0, nums.length);
return nums;
}
public int[] shuffle() {
Random random = new Random();
int length = nums.length;
//洗牌算法
for (int i = 0; i < length; i++) {
//nextInt(bound):随机生成 [0, bound) 之间的一个整数并返回
int j = i + random.nextInt(length - i);
//交换 nums[i] 和 nums[j]
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
return nums;
}
}
/**
* 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();
*/
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_43004044/article/details/125580977
内容来源于网络,如有侵权,请联系作者删除!