题目

image.png

解题思路

  1. /*
  2. n is the size of the array
  3. [0...n - 1]
  4. i [i, n-1]
  5. i = 0, [0, n - 1] 1 / n
  6. i = 1, [1, n - 1] ( (n - 1) / n ) * ( 1 /(n - 1)) = 1 /
  7. i = 2 ( (n - 1) / n ) * ( n - 2 /(n - 1)) * (n - 2 / n - 1) = 1 / n
  8. [i, n - 1]
  9. [0, n - 1 - i] + i
  10. */

作者:venturekwok
链接:https://leetcode-cn.com/problems/shuffle-an-array/solution/c-jian-dan-xi-pai-suan-fa-si-lu-qing-xi-pu41a/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

解题代码

  1. class Solution {
  2. int[] nums;
  3. //构造函数,初始化
  4. public Solution(int[] nums) {
  5. this.nums = nums;
  6. }
  7. //重置
  8. public int[] reset() {
  9. return nums;
  10. }
  11. //洗牌算法
  12. public int[] shuffle() {
  13. if(nums == null) return null;
  14. int[] res = nums.clone();
  15. for(int i = 0 ; i < nums.length; i++ ) {
  16. int random = (int) ( Math.random() * (nums.length - i) ) + i; //[0,1) [i,nums.length -1]
  17. swap(res,i,random);
  18. }
  19. return res;
  20. }
  21. public void swap(int[] res, int i, int random) {
  22. int temp = res[i];
  23. res[i] = res[random];
  24. res[random] = temp;
  25. }
  26. }
  27. /**
  28. * Your Solution object will be instantiated and called as such:
  29. * Solution obj = new Solution(nums);
  30. * int[] param_1 = obj.reset();
  31. * int[] param_2 = obj.shuffle();
  32. */
class Solution {

    int [] nums;
    int [] shuffle;
    public Solution(int[] nums) {
        this.nums = nums;
    }

    public int[] reset() {
        return nums;
    }

    public int[] shuffle() {
        int length = nums.length;
        shuffle = nums.clone(); //传值
        for (int i = 0; i < length; i++) {
            int random = (int)(Math.random() * (length - i )) + i;
            swap(i,random);
        }
        return shuffle;
    }

    public void swap(int i ,int j) {
        if(i == j) return ; //相同则不进行交换
        shuffle[i] ^= shuffle[j];
        shuffle[j] ^= shuffle[i];
        shuffle[i] ^= shuffle[j];
    }
}

/**
 * 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();
 */