leetcode_398 随机数索引

101 阅读1分钟

要求

给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。

注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。

示例:

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);

核心代码

class Solution:
    def __init__(self, nums: List[int]):
        self.nums = nums
        self.n = len(nums)

    def pick(self, target: int) -> int:
        res = []
        for i in range(self.n):
            if self.nums[i] == target:
                res.append(i)
        return random.choice(res)

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

image.png

解题思路:主要是理解数据结构,就是我们需要将相同的值的索引,最终以随机的方式返回去即可,比较简单。