GuilinDev

Lc0384

05 August 2008

384 Shuffle an Array

随机shuffle array中的元素

Knuth洗牌算法,对于下标为 0 位置,从 [0, n - 1] 随机一个位置进行交换,共有 nn 种选择;下标为 11 的位置,从 [1, n - 1] 随机一个位置进行交换,共有 n - 1 种选择 ,以此类推

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {

    int len;
    int[] originalArr;
    Random random = new Random();
    public Solution(int[] nums) {
        len = nums.length;
        originalArr = nums;
        random = new Random();
    }
    
    public int[] reset() {
        return originalArr;
    }
    
    public int[] shuffle() {
        // 要是不用reset只要求shuffle的话,这个数组可不要,O(1)
        int[] result = originalArr.clone();
        for (int i = 0; i < len; i++) {
            swap(result, i, i + random.nextInt(len - i));
        }
        return result;
    }
    
    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[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();
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {

    private int[] nums;
    
    public Solution(int[] nums) {
        this.nums = nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] rand = new int[nums.length];
        for (int i = 0; i < nums.length; i++){
            int r = (int) (Math.random() * (i+1));
            rand[i] = rand[r];
            rand[r] = nums[i];
        }
        return rand;
    }
}

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