[LeetCode Python3] 382. Linked List Random Node + 水塘抽样 +大数据流,等概率抽样

382. Linked List Random Node

class Solution:
    def __init__(self, head: ListNode):
        self.head = head
    def getRandom(self) -> int:
        count = 0
        reserve = self.head.val
        cur = self.head
        while cur:
            count += 1
            rand = random.randint(1, count)
            if rand == count:
                reserve = cur.val
            cur = cur.next
        return reserve

类似的大数据流,要求等概率地取其中k个数,均可以采用“水塘抽样”算法。详细介绍

你可能感兴趣的:(LeetCode每日一题)