[LeetCode] Random Pick Index

398. Random Pick Index

Given an integer array nums 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.

Implement the Solution class:

  • Solution(int[] nums) Initializes the object with the array nums.
  • int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i’s, then each index should have an equal probability of returning.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
unordered_map<int, vector<int>> m;
public:
Solution(vector<int>& nums) {
for(int i = 0; i < nums.size(); i++) {
m[nums[i]].push_back(i);
}
}

int pick(int target) {
auto v = m[target];
auto idx = rand()%m.size();

return v[idx];
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* int param_1 = obj->pick(target);
*/

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/28/PS/LeetCode/random-pick-index/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.