LeetCode 398 Random Pick Index
概述
https://leetcode.com/problems/random-pick-index/
暴力解
遍历数组,将每个 target 对应的 idx 存入哈希表。
class Solution {
public:
unordered_map<int, vector<int>> m;
Solution(vector<int>& nums) {
for (int i = 0; i < nums.size(); i++) m[nums[i]].push_back(i);
}
int pick(int target) {
int r = rand() % m[target].size();
return m[target][r];
}
};