382. 链表随机节点

原理参考:蓄水池抽样——《编程珠玑》读书笔记
思路:以1/m的概率选择第m个对象
思路

class Solution:
    def __init__(self, head: ListNode):
        p = head
        self.vals = []
        while p:
            self.vals.append(p.val)
            p = p.next
        self.n = len(self.vals)

    def getRandom(self) -> int:
        import random
        index = random.randrange(0,self.n)
        return self.vals[index]

在这里插入图片描述
进阶:
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?

class Solution:
    def __init__(self, head: ListNode):
        self.head = head
        
    def getRandom(self) -> int:
        import random
        ans,cur,count = self.head.val,self.head.next,1
        while cur:
            count+=1
            if random.randrange(0,count)==0: #这个成立的概率是1/count
                ans = cur.val
            cur = cur.next
        return ans

在这里插入图片描述

发布了115 篇原创文章 · 获赞 4 · 访问量 5017

猜你喜欢

转载自blog.csdn.net/qq_27921205/article/details/104331394