美文网首页
398. 随机数索引

398. 随机数索引

作者: 编程小王子AAA | 来源:发表于2020-08-17 09:30 被阅读0次

蓄水池算法

给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。

注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。

示例:

int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);

// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);

// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);


class Solution {

    int[] nums=null;
    Random r=null;
    public Solution(int[] nums) {
        this.nums=nums;
        this.r=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){
                // 如果等于target,计数器加1
                count++;
                //开始抽样,在[0,count)范围内随机生成一个数字
                //现在是容量为1的水池抽样,对应模型中的r<k,
                // 如果这个数字是0,我们将res赋值为i即可
                //否则,继续循环
                if(r.nextInt(count)==0){
                    res=i;
                }else{
                    continue;
                }
            }
        }
        return res;
    }
}
/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */

相关文章

  • LC吐血整理之Random篇

    所有题解方法请移步 github-Leecode_summary 384.打乱数组 & 398.随机数索引 set...

  • 398. 随机数索引

    蓄水池算法 给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组...

  • 398. 随机数索引(Python)

    题目 难度:★★☆☆☆类型:数组方法:数学 力扣链接请移步本题传送门更多力扣中等题的解决方案请移步力扣中等题目录 ...

  • LeetCode 398. 随机数索引

    1.题目 https://leetcode-cn.com/problems/random-pick-index/ ...

  • 398. 随机数索引 - 每日一题

    给你一个可能含有 重复元素 的整数数组 nums ,请你随机输出给定的目标数字 target 的索引。你可以假设给...

  • LeetCode专题-编写特定用途的数据结构

    398. Random Pick Index Medium Given an array of integers ...

  • numpy 通用函数2.0

    数组的变换,复制,索引,基本运算,堆叠,拆分,运算,随机数 数组形状:.T/.reshape()/.resize(...

  • 398:随机数索引

    题意 给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。 ...

  • 常用负载均衡算法

    1.随机 获取服务列表大小范围内的随机数,将随机数作为列表索引, 从服务列表中获取服务提供者。 2.加权随机 按照...

  • LeetCode 398 随机数索引

    题目 https://leetcode-cn.com/problems/random-pick-index/ 题解...

网友评论

      本文标题:398. 随机数索引

      本文链接:https://www.haomeiwen.com/subject/qiypdktx.html