398. 随机数索引

 1 class Solution 
 2 {
 3     unordered_map<int,vector<int>> hash;// 对应的数 + /下标(可能有重复数)/
 4 public:
 5     Solution(vector<int>& nums) 
 6     {
 7         for(int i = 0;i < nums.size();i ++) hash[nums[i]].push_back(i);
 8     }
 9     
10     int pick(int target) 
11     {
12         int index = rand() % hash[target].size();
13         return hash[target][index];
14     }
15 };

 

posted @ 2020-04-28 18:39  Jinxiaobo0509  阅读(83)  评论(0)    收藏  举报