LeetCode 题解工作台
随机数索引
给你一个可能含有 重复元素 的整数数组 nums ,请你随机输出给定的目标数字 target 的索引。你可以假设给定的数字一定存在于数组中。 实现 Solution 类: Solution(int[] nums) 用数组 nums 初始化对象。 int pick(int target) 从 nums…
4
题型
4
代码语言
3
相关题
当前训练重点
中等 · 哈希·数学
答案摘要
class Solution: def __init__(self, nums: List[int]):
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·数学 题型思路
题目描述
给你一个可能含有 重复元素 的整数数组 nums ,请你随机输出给定的目标数字 target 的索引。你可以假设给定的数字一定存在于数组中。
实现 Solution 类:
Solution(int[] nums)用数组nums初始化对象。int pick(int target)从nums中选出一个满足nums[i] == target的随机索引i。如果存在多个有效的索引,则每个索引的返回概率应当相等。
示例:
输入 ["Solution", "pick", "pick", "pick"] [[[1, 2, 3, 3, 3]], [3], [1], [3]] 输出 [null, 4, 0, 2] 解释 Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // 随机返回索引 2, 3 或者 4 之一。每个索引的返回概率应该相等。 solution.pick(1); // 返回 0 。因为只有 nums[0] 等于 1 。 solution.pick(3); // 随机返回索引 2, 3 或者 4 之一。每个索引的返回概率应该相等。
提示:
1 <= nums.length <= 2 * 104-231 <= nums[i] <= 231 - 1target是nums中的一个整数- 最多调用
pick函数104次
解题思路
方法一
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def pick(self, target: int) -> int:
n = ans = 0
for i, v in enumerate(self.nums):
if v == target:
n += 1
x = random.randint(1, n)
if x == n:
ans = i
return ans
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate understanding of efficient random selection techniques.
- question_mark
Look for clear explanation of hash table usage for storing indices.
- question_mark
Evaluate how well the candidate explains reservoir sampling and its role in equal probability selection.
常见陷阱
外企场景- error
Failing to use a hash table for efficient index retrieval.
- error
Incorrectly implementing random selection without equal probability for each index.
- error
Not accounting for multiple calls to `pick` and how to handle them efficiently.
进阶变体
外企场景- arrow_right_alt
Add constraints that limit the number of indices for each target.
- arrow_right_alt
Implement the solution with a different random selection method, such as using random numbers and modulo operations.
- arrow_right_alt
Explore how this approach can be extended to support multi-dimensional arrays or lists of lists.