哈希表 水塘抽样
方法一 哈希表
思路分析
建立一个key为数组,value为位置数组的哈希表根据题意模拟即可。
参考代码
class Solution:def __init__(self, nums: List[int]):self.pos = collections.defaultdict(list)for i,num in enumerate(nums):self.pos[num].append(i)def pick(self, target: int) -> int:return random.choice(self.pos[target])
复杂度分析
时间复杂度 O(n) 主要时间复杂度都在建立哈希表的遍历过程。n为数组长度
空间复杂度 O(n) 哈希表的存储
方法二 水塘抽样
思路分析
当遍历到第i个元素的时候有的概率将其保留下来。证明过程可以看水塘抽样算法
参考代码
class Solution:def __init__(self, nums: List[int]):self.nums = numsdef pick(self, target: int) -> int:ans = cnt = 0for n,num in enumerate(self.nums):if num == target:cnt += 1# 当 cnt = 1 的时候 randrange(cnt)必等于0所以这里必定会走一次if random.randrange(cnt) == 0:ans = nreturn ans
复杂度分析
时间复杂度 O(n) n为数组长度
空间复杂度 O(1)
