382. Linked List Random Node
- Total Accepted: 23716
- Total Submissions: 51037
- Difficulty: Medium
- Contributor: LeetCode
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();
Subscribe to see which companies asked this question.
题目链接:https://leetcode.com/problems/linked-list-random-node/#/description
解题思路:题目意思是给定一个链表,随机输出链表中的一个数,要求每个数输出的概率相等。蓄水池抽样可定义为:在不知总个数的情况下,等概率地抽取这组数中的某个数。核心思想是:1、初始答案为第一个数,此时链表的下标指向第一个数,即此时第一个数被选中的概率为1;
2、下标后移一位指向第二个数,用Random函数随机抽取0-1的数,抽取的范围是2,抽中1的概率为1/2,如果抽中1,把答案改为此时下标所指的数,否则不改变答案的值。
3、以此类推,用Random函数抽取的范围不断加1,即Random rd = new Random(i),抽取范围为i,从0 -( i-1)中取道 i-1 的概率为1 / i。如果抽中i-1,把答案改为此时下标所指的数,否则不改变答案的值。
4、直到链表为空,得到答案;
第 i 个数被选中的概率为它被选中的概率:1 / i ,乘以后面的数不被选中的概率:[ i / ( i + 1 ) ] * [ ( i + 1 ) / ( i + 2 ) ] *... * [ ( n - 1 ) / ( n + 1 )]
即P(第 i 个数被选中) = ( 1 / i )* [ i / ( i + 1 ) ] * [ ( i + 1 ) / ( i + 2 ) ] *... * [ ( n - 1 ) / ( n + 1 )] = 1 / n
代码如下:
(leetcode提交代码)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
static ListNode h = null;
/** @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.h = head;
}
/** Returns a random node's value. */
public int getRandom() {
Random rd = new Random ();
int ans = -1;
int idx = 0;
ListNode p = h;
while(p!=null){
idx++;
int rn = rd.nextInt(idx);
if(rn==idx-1){
ans = p.val;
}
p = p.next;
}
return ans;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
eclipse 上代码:
import java.util.Random;
public class Main {
static class ListNode {
int val;
ListNode next;
ListNode(int x)
{ val = x; }
}
static ListNode h = null;
public Main(ListNode head) {
this.h = head;
}
public static int getRandom() {
Random rd = new Random ();
int ans = -1;
int idx = 0;
ListNode p = h;
while(p!=null){
idx++;
int rn = rd.nextInt(idx);
if(rn==idx-1){
ans = p.val;
}
p = p.next;
}
return ans;
}
public static void main(String[] args){
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Main obj = new Main(head);
System.out.println(obj.getRandom());
}
}