LeetCode_洗牌算法_中等_384.打乱数组

x33g5p2x  于2022-07-04 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(381)

1.题目

给你一个整数数组 nums ,设计算法来打乱一个没有重复元素的数组。打乱后,数组的所有排列应该是 等可能 的。

实现 Solution class:

  1. Solution(int[] nums) 使用整数数组 nums 初始化对象
  2. int[] reset() 重设数组到它的初始状态并返回
  3. int[] shuffle() 返回数组随机打乱后的结果

示例 1:

  1. 输入
  2. ["Solution", "shuffle", "reset", "shuffle"]
  3. [[[1, 2, 3]], [], [], []]
  4. 输出
  5. [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
  6. 解释
  7. Solution solution = new Solution([1, 2, 3]);
  8. solution.shuffle(); // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如,返回 [3, 1, 2]
  9. solution.reset(); // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]
  10. 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

2.思路

(1)洗牌算法
有关洗牌算法可以参考洗牌算法详解:你会排序,但你会打乱吗?这篇文章。

3.代码实现(Java)

  1. //思路1————洗牌算法
  2. class Solution {
  3. //当前数组
  4. int[] nums;
  5. //初始数组
  6. int[] oriNums;
  7. public Solution(int[] nums) {
  8. this.nums = nums;
  9. this.oriNums = new int[nums.length];
  10. //将 nums 中的元素复制到 oriNums 中
  11. System.arraycopy(nums, 0, oriNums, 0, nums.length);
  12. }
  13. public int[] reset() {
  14. //将 oriNums 中的元素复制到 nums 中,即完成回到初始化状态
  15. System.arraycopy(oriNums, 0, nums, 0, nums.length);
  16. return nums;
  17. }
  18. public int[] shuffle() {
  19. Random random = new Random();
  20. int length = nums.length;
  21. //洗牌算法
  22. for (int i = 0; i < length; i++) {
  23. //nextInt(bound):随机生成 [0, bound) 之间的一个整数并返回
  24. int j = i + random.nextInt(length - i);
  25. //交换 nums[i] 和 nums[j]
  26. int tmp = nums[i];
  27. nums[i] = nums[j];
  28. nums[j] = tmp;
  29. }
  30. return nums;
  31. }
  32. }
  33. /**
  34. * Your Solution object will be instantiated and called as such:
  35. * Solution obj = new Solution(nums);
  36. * int[] param_1 = obj.reset();
  37. * int[] param_2 = obj.shuffle();
  38. */

相关文章