java 398.随机选择指数(#1水库采样).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 398.随机选择指数(#1水库采样).java相关的知识,希望对你有一定的参考价值。

class Solution {
    
    private Random rand;
    private int[] nums;
    public Solution(int[] nums) {
        rand = new Random();
        this.nums = nums;
    }
    
    
    public int pick(int target) {
        int count = 0, res = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != target)
                continue;
            if (rand.nextInt(count + 1) == count) {
                res = i;
            }
            count++;
        }
        return res;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */
class Solution {
    
    private Random rand;
    private int[] nums;
    public Solution(int[] nums) {
        rand = new Random();
        this.nums = nums;
    }
    
    
    public int pick(int target) {
        int count = 0, res = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != target)
                continue;
            if (rand.nextInt(++count) == 0) {
                res = i;
            }
        }
        return res;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */

以上是关于java 398.随机选择指数(#1水库采样).java的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 水库采样

398. 随机数索引

CF398B题解

[398]. 随机数索引

[398]. 随机数索引

自助法随机采样过程中,对n个样本进行n次有放回的随机采样,当n趋向于无穷大时,最终有多少数据从未被选择过?