Leetcode382-随机抽样

该博客讨论了如何在给定的单链表中实现随机抽取节点的问题,确保每个节点被选择的概率相等。即使链表长度极大且未知,也要能有效地解决此问题。文章提供了思路和代码参考。
摘要由CSDN通过智能技术生成

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

 

给定一个单链表,随机抽取一个节点,使得每个节点被抽取的概率相等。单链表长度很大,并且长度未知

思路:

 

代码:

public class Solution {
    ListNode head = null;
    Random r = new Random();

    public Solution(ListNode head) {
        this.head = head;
    }
    
    public int getRandom() {
        int result = this.head.val;
        ListNode node = this.head.next;
        int k =1;
        int i = 1;
        while(node != null){
            double x = r.nextDouble();
            double y = k / (k+i *1.0);           
            if(x <= y){
                result = node.val;
            }
            
            i++;
            node = node.next;
        }
        
        return result;
    }
}

参考:

http://blog.jobbole.com/42550/

https://gregable.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值