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:

1
2
3
4
5
6
7
8
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);

思路

我们如果以牺牲空间复杂度来换取时间复杂度的话,可以在初始化Solution类的时候指定一个字典对对应的pickup值进行存储。这样就可以在短时间内(接近于O(1)的时间)来实现查找了。这是最原始的方法了。

但是如果又要保证空间复杂度,又要保证时间复杂度,就要采用蓄水池抽样的方法了。详情可以查看参考资料。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import copy
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.pickmap = {}
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
res = []
if (self.pickmap.has_key(target)):
res = self.pickmap[target]
else:
for index, i in enumerate(self.nums):
if (i == target):
res.append(index)
self.pickmap[target] = copy.copy(res)
return random.choice(res)
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)

me?https://discuss.leetcode.com/topic/58659/clean-understandable-o-1-momery-o-n-time-java-solution 参考资料:蓄水池抽样——http://www.cnblogs.com/HappyAngel/archive/2011/02/07/1949762.html