[二分搜索] leetcode 528 Random Pick with Weight
problem:https://leetcode.com/problems/random-pick-with-weight/
首先计算一个累积的频数,根据总频数来进行随机,之后通过二分查找得到当前随机数对应的下标。
class Solution { public: vector<int> sum; int count; unordered_map<int, int> mapIndex; Solution(vector<int>& w) { for (int i = 0; i < w.size(); i++) { if (w[i] != 0) { int num = sum.size() > 0 ? sum.back() + w[i] : w[i]; sum.push_back(num); mapIndex[num] = i; } } count = sum.size() ? sum.back() : 0; } int pickIndex() { if (count == 0) return -1; int index = rand() % count; auto it = upper_bound(sum.begin(), sum.end(), index); return mapIndex[*it]; } };

浙公网安备 33010602011771号