LeetCode 382 Linked List Random Node

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?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

大意是说给你一个链表,长度未知,等概率随机选出一个。这就需要蓄水池算法。
蓄水池算法用于解决在N个元素中等概率随机选出k个(0<k<N).N可以未知或者很大。
具体做法如下:
1 给N个元素标号为1-N
2 遍历,将前k个元素加入候选集合
3 当标号大于k时,假设为i,如果元素只有i个,那么每个元素被选中的概率应该是k/i,为此做如下操作:
对第i个元素,以k/i的概率将i号元素加入候选集合,以1/k的概率从候选集合中移除一个原来元素。如果每个元素留在集合的概率是i/k那么算法就正确。
证明(数学归纳法):
3.1 当i=k+1时,第i个元素加入候选集合的概率是1/i,前i个元素被留下概率是1-(k/(k+1))*(1/k)=k/(k+1)
3.2 当i>k时,假设前i个元素每一个被加入候选集合的概率是k/i
3.3 当i=i+1时,前i个元素每一个被加入候选集合的概率是(k/i)*(1-(k/(i+1))*(1/k)),化简可得k/(i+1),第i+1个显然也是k/(i+1)
3.4 得证
具体到这个题只要把k换成1就行了。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random ran = new Random();
        System.out.println(ran.nextInt(1));
    }
    public class ListNode {
        int val;
        ListNode next;
 
        ListNode(int x) {
            val = x;
        }
    }
 
    ListNode head;
    Random ran;
 
    public Solution_382(ListNode head) {
        this.head = head;
        ran = new Random();
    }
 
    /** Returns a random node's value. */
    public int getRandom() {
        ListNode node = head;
        int current = 0;
        for (int i = 1; node != null; i++) {
            current = ran.nextInt(i) == 0 ? node.val : current;
            node=node.next;
        }
        return current;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值