Problem:
https://leetcode.com/problems/random-pick-index/description/
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: Reservoir sampling
https://en.wikipedia.org/wiki/Reservoir_sampling
Time complexity: O(query * n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua // Running time: 92 ms class Solution { public: Solution(vector<int> nums) { nums_ = std::move(nums); } int pick(int target) { int n = 0; int index = -1; for (int i = 0; i < nums_.size(); ++i) { if (nums_[i] != target) continue; ++n; if (rand() % n == 0) index = i; } return index; } private: vector<int> nums_; }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment