382. Linked List Random Node (蓄水池抽樣,java)

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());
    }
}



發佈了185 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章