<Random> 384 398

384. Shuffle an Array

random.nextInt(n) 返回[0, n) 的随机数,故要+1;

class Solution {
    
    private int[] nums;
    private Random random;
    
    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }
    
    /** 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() {
        if(nums == null)    return null;
        
        int[] a = nums.clone();
        for(int j = 1; j < a.length; j++){
            int i = random.nextInt(j + 1);
            swap(a, i , j);
        }
        return a;
    }
    
    private void swap(int[] a, int i, int j){
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}

398. Random Pick Index

2 : It's probability of selection is 1 * (1/2) * (2/3) = 1/3
3 : It's probability of selection is (1/2) * (2/3) = 1/3
4 : It's probability of selection is just 1/3

class Solution {

    int[] nums;
    Random random;
    
    public Solution(int[] nums) {
        this.nums = nums;
        this.random = new Random();
    }
    
    public int pick(int target) {
        int res = -1;
        int count = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] != target)
                continue;
            if(random.nextInt(++count) == 0)
                res = i;
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/Afei-1123/p/11840861.html