原理参考:蓄水池抽样——《编程珠玑》读书笔记
思路:以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