0
点赞
收藏
分享

微信扫一扫

LeetCode中等题之随机数索引

爪哇驿站 2022-04-25 阅读 34

题目

给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。
示例:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);
// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);
来源:力扣(LeetCode)

解题思路

  一个简单的思路就是,建立一个键值对,键是数组的元素,值是一个list用来存放键在原数组中的下标。

class Solution:

    def __init__(self, nums: List[int]):
        self.d=dict()
        for i in range(len(nums)):
            if nums[i] in self.d.keys():
                self.d[nums[i]].append(i)
            else:
                self.d[nums[i]]=[i]

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


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

在这里插入图片描述

举报

相关推荐

0 条评论