题目描述
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);
算法
(蓄水池抽样)
利用一个unordered_map<int, vector<int>> um
存储每个数值对应的下标,那么随机返回一个索引,其实就是生成一个0-um[target].size() - 1
的一个随机数,这样如果存在多次pick
,那么每次都是$O(1)$的效率。
C++ 代码
class Solution {
unordered_map<int, vector<int>> um;
public:
Solution(vector<int>& nums) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n = nums.size();
for (int i = 0; i < n; ++i) {
um[nums[i]].push_back(i);
}
}
int pick(int target) {
int len = um[target].size();
int pos = rand() % len;
return um[target][pos];
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* int param_1 = obj->pick(target);
*/