實現一個等可能返回任意節點的鏈表 Linked List Random Node

問題: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?dom

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

解決:this

① 先統計出鏈表的長度,而後根據長度隨機生成一個位置,而後從開頭遍歷到這個位置便可。spa

class Solution { //142ms
    ListNode head;
    int len;
    /** @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.head = head;
        ListNode cur = head;
        while(cur != null){
            len ++;
            cur = cur.next;
        }
    }
    /** Returns a random node's value. */
    public int getRandom() {
        Random random = new Random();
        int next = random.nextInt(len);
        ListNode cur = head;
        while(next != 0){
            next --;
            cur = cur.next;
        }
        return cur.val;
    }
}.net

蓄水池抽樣(Reservoir Sampling )是一個頗有趣的問題,它可以在o(n)時間內對n個數據進行等機率隨機抽取,例如:從1000個數據中等機率隨機抽取出100個。另外,若是數據集合的量特別大或者還在增加(至關於未知數據集合總量),該算法依然能夠等機率抽樣對象

蓄水池抽樣:從N個元素中隨機的等機率的抽取k個元素,其中N沒法肯定。ci

先給出代碼:element

Init : a reservoir with the size: k
        for    i= k+1 to N
        M=random(1, i);
        if( M < k)
        SWAP the Mth value and ith value
        end for

上述僞代碼的意思是:先選中第1到k個元素,做爲被選中的元素。而後依次對第k+1至第N個元素作以下操做:

每一個元素都有k/x的機率被選中,而後等機率的(1/k)替換掉被選中的元素。其中x是元素的序號。

解法:咱們老是選擇第一個對象,以1/2的機率選擇第二個,以1/3的機率選擇第三個,以此類推,以1/m的機率選擇第m個對象。當該過程結束時,每個對象具備相同的選中機率,即1/n,證實以下。

 證實:第m個對象最終被選中的機率P = 選擇m的機率 * 其後面全部對象不被選擇的機率,即

①  鏈表可能很長,咱們無法提早知道長度。因此使用蓄水池抽樣來解決,具體步驟以下:

一、初始答案爲第一個數,此時鏈表的下標指向第一個數,即此時第一個數被選中的機率爲1;

二、下標後移一位指向第二個數,用Random函數隨機抽取0-1的數,抽取的範圍是2,抽中1的機率爲1/2,若是抽中1,把答案改成此時下標所指的數,不然不改變答案的值。

三、以此類推,用Random函數抽取的範圍不斷加1,即Random rd = new Random(i),抽取範圍爲i,從0 -( i-1)中取到 i-1 的機率爲1 / i。若是抽中i-1,把答案改成此時下標所指的數,不然不改變答案的值。

四、直到鏈表爲空,獲得答案;

第 i 個數被選中的機率爲它被選中的機率:1 / i ,乘之後面的數不被選中的機率:[ i / ( i + 1 ) ] * [ ( i + 1 ) / ( i + 2 ) ] *... * [ ( n  - 1 ) / ( n  )]

即P(第 i 個數被選中) = (  1 / i  )* [ i / ( i + 1 ) ] * [ ( i + 1 ) / ( i + 2 ) ] *... * [ ( n  - 1 ) / ( n)] = 1 / n 。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {//135ms
    ListNode head;
    Random random;
    /** @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.head = head;         random = new Random();     }     /** Returns a random node's value. */     public int getRandom() {         ListNode res = null;         ListNode cur = head;         for (int i = 1;cur != null;i ++){             if (random.nextInt(i) == 0){                 res = cur;             }             cur = cur.next;         }         return res.val;     } } /**  * Your Solution object will be instantiated and called as such:  * Solution obj = new Solution(head);  * int param_1 = obj.getRandom();  */

相關文章
相關標籤/搜索