398. Random Pick Index &&382. Linked List Random Node 蓄水池原理

本文介绍了一种随机采样算法——蓄水池算法的应用,包括如何从数组中随机选择指定值的索引,以及如何随机返回链表中的一个节点。算法在遍历过程中保持随机性,适用于大数据集。

蓄水池原理应用:

随机返回n个元素中的某个元素,从0开始遍历这n个元素 用count记录遍历过得元素数目(符合要求的元素在数,比如数值等于target的数组索引),如果random(count)==0 则选中这个元素。 可以证明 在遍历的过程中 随着遍历元素数目的增加 random(count)==0  的几率是随机均等的


Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:

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

// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);

// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
蓄水池问题:

随机产生一个 索引 其值等于给定的target。  等于target的索引有很多 需要随机


关键 产生一个随机数[0,count) 范围内的随机数如果这个数等于0  则选中该索引值。(在[0,count)范围内产生一个值等于0的概率为1/count) 一共有count个符合条件的数


public class Solution {
    int []nums;
    Random ran;
    public Solution(int[] nums) {
        this.nums=nums;
        this.ran=new Random();
    }
    
    public int pick(int target) {
        int count=0;
        int result=0;
        for(int i=0;i<nums.length;i++){
            if(target!=nums[i])
                continue;
            if(ran.nextInt(++count)==0)
                result =i;
        }
        return result;
    }
}

随机返回链表中的一个节点:



public class Solution {
    ListNode head;
    
    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    public Solution(ListNode head) {
        this.head=head;
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        Random ran=new Random();
        ListNode dummy=head;
        int result=0;
        // ListNode dummy=null;
        for(int i=1;dummy!=null;i++){
            if(ran.nextInt(i)==0)
                result=dummy.val;
            dummy=dummy.next;
        }
        
        // return dummy.val;
        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值