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;
}
}
参考: