首页 > 其他 > 详细

<Random> 384 398

时间:2019-11-12 13:30:28      阅读:78      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

<Random> 384 398

原文:https://www.cnblogs.com/Afei-1123/p/11840861.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!