398. Random Pick Index
https://leetcode.com/problems/random-pick-index/
solution
# 蓄水池算法: 给定数据流,长度N很大,且N直到处理完所有数据之前都不可知,如何在只遍历一遍数据(O(N))的情况下,随机选取出m个不重复的数据
# i <= m: i从1开始,小于m则直接入池
# i > m: 从[1, i]中选一个数x, x > m 掠过;x<=m, x位置的元素替换为i位置的元素
# https://zhuanlan.zhihu.com/p/119329875
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def pick(self, target: int) -> int:
count = 0
res = None
for i, num in enumerate(self.nums):
if num == target:
count += 1
if random.randint(1, count) == 1:
res = i
return res时间复杂度:O(n) 空间复杂度:O(1)
follow up-Reservoir Sampling/Rejection Sampling类
多线程版本
380. Insert Delete GetRandom O(1)
497. Random Point in Non-overlapping Rectangles
381. Insert Delete GetRandom O(1) - Duplicates allowed
470. Implement Rand10() Using Rand7()
478. Generate Random Point in a Circle
Last updated