LeetCode 382. Linked List Random Node

題目描述:

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

題目大意:

給定一個單鏈表,返回鏈表中一個隨機節點的值。每一個節點應該被等可能的抽取。

進一步思考:

如果鏈表很大並且長度未知呢?你可以不使用額外的空間高效地解決此問題嗎?

解題思路:

蓄水池抽樣(Reservoir Sampling)

蓄水池抽樣算法的等概率性可以用數學歸納法證明:

I   當鏈表長度爲1時,random.randint(0, 0)恆等於0,因此抽到第1個元素的概率爲1

II  假設抽取前n個元素的概率相等,均爲1/n

III 當抽取第n+1個元素時:

若random.randint(0, n)等於0,則返回值替換爲第n+1個元素,其概率爲1/(n+1);

否則,抽取的依然是前n個元素,其概率爲1/n * n/(n+1) = 1/(n+1)

Python代碼:

import random
class Solution(object):

    def __init__(self, head):
        “””
        @param head The linked list’s head. Note that the head is guanranteed to be not null, so it contains at least one node.
        :type head: ListNode
        “”“
        self.head = head

    def getRandom(self):
        “””
        Returns a random node’s value.
        :rtype: int
        “”“
        cnt = 0
        head = self.head
        while head:
            if random.randint(0, cnt) == 0:
                ans = head.val
            head = head.next
            cnt += 1
        return ans
      

本文鏈接:http://bookshadow.com/weblog/2016/08/10/leetcode-linked-list-random-node/
請尊重作者的勞動成果,轉載請註明出處!書影博客保留對文章的所有權利。

如果您喜歡這篇博文,歡迎您捐贈書影博客: ,查看支付寶二維碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章