力扣 随机数索引 Python

力扣 随机数索引 Python,第1张

文章目录
  • 题目
  • 哈希表索引

题目


提示:参考力扣官方题解

哈希表索引

时间复杂度 O(n)

空间复杂度O(n)

from collections import defaultdict
from secrets import choice


class Solution:

    def __init__(self, nums: List[int]):
        self.pos = defaultdict(list)
        for i, num in enumerate(nums):
            self.pos[num].append(i)

    def pick(self, target: int) -> int:
        return choice(self.pos[target])


# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/738292.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存