384. Shuffle an Array(打乱数组)

水深无声 2022-07-14 01:29 300阅读 0赞

Shuffle a set of numbers without duplicates.

Example:

  1. // Init an array with set 1, 2, and 3.
  2. int[] nums = {1,2,3};
  3. Solution solution = new Solution(nums);
  4. // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
  5. solution.shuffle();
  6. // Resets the array back to its original configuration [1,2,3].
  7. solution.reset();
  8. // Returns the random shuffling of array [1,2,3].
  9. solution.shuffle();

题目大意:打乱一个数组,要求在打乱之后,产生的各种结果出现的概率都是相同的。例如原数组为{1,2,3},那么打乱后结果为{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,2,1},{3,1,2}的概率各为 1/6。

解题思路:

使用一个数组 orgn[] 用于保存数组的原始顺序,另一个数组 cur[] 用于工作。

构造方法:给 orgn[] 赋值;

reset方法:返回 orgn[] 数组;

shuffle方法:先用 orgn[] 数组初始化 cur[] 数组,然后从右往左遍历 cur[] 数组,即cur[i],i 从 len-1 到 0,对于cur[i] ,任何 cur[j],(j<=i),cur[j] 都有 1/(i+1)的可能性与cur[i] 进行交换。代码如下:(250ms,beats 70.73%)

  1. public class Solution {
  2. private int[] orgn;
  3. private int[] cur;
  4. public Solution(int[] nums) {
  5. orgn = nums;
  6. }
  7. /** Resets the array to its original configuration and return it. */
  8. public int[] reset() {
  9. return orgn;
  10. }
  11. /** Returns a random shuffling of the array. */
  12. public int[] shuffle() {
  13. int len = orgn.length;
  14. cur = new int[len];
  15. for(int i=0;i<len;i++)
  16. cur[i] = orgn[i];
  17. int pos;//记录要交换元素的位置
  18. int temp; //记录要交换的值
  19. Random ran = new Random();
  20. for(int i=len-1;i>=0;i--){
  21. pos = ran.nextInt(i+1);
  22. temp = cur[pos];
  23. cur[pos] = cur[i];
  24. cur[i] = temp;
  25. }
  26. return cur;
  27. }
  28. }

发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读