problem:https://leetcode.com/problems/random-pick-with-weight/
First, a cumulative frequency of calculation, according to the total number of random frequency, then find the corresponding random number to obtain the current index by half.
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]; } };