原题
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
解法
使用字典, 键是nums中的数字, values是数字的索引列表, 然后使用random.choice从列表中随机选择一个index即可.
代码
class Solution:
def __init__(self, nums: 'List[int]'):
self.data = collections.defaultdict(list)
for i, n in enumerate(nums):
self.data[n].append(i)
def pick(self, target: 'int') -> 'int':
return random.choice(self.data[target])
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
本文介绍了一种在含重复元素的整数数组中,针对给定目标数字随机返回其索引位置的算法实现。该算法利用字典存储数组中每个数字的所有索引,通过随机选择实现目标数字索引的等概率返回,适用于大数据量场景。

270

被折叠的 条评论
为什么被折叠?



