题目链接:382. 链表随机节点
蓄水池抽样算法。
import random
from typing import Optional
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def __init__(self, head: Optional['ListNode']):
self.head = head
def getRandom(self) -> Optional[int]:
if self.head is None:
return None
target, cur, counter = None, self.head, 0
while cur is not None:
if target is None:
target = cur.val
elif random.randint(0, counter) < 1:
target = cur.val
cur, counter = cur.next, counter + 1
return target
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()