xinyu04

导航

[Google] LeetCode 528 Random Pick with Weight

You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.

You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).

For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).

Solution

既然是加权重, 那么不妨直接利用前缀和将其展开到坐标轴上面,这样每一段的长度就是权重的大小,然后利用 \(upper\_bound\) 即可

点击查看代码
class Solution {
private:
    vector<int> seg;
public:
    Solution(vector<int>& w) {
        int n = w.size();
        for(int i=0;i<n;i++){
            if(!i)seg.push_back(w[i]);
            else{
                seg.push_back(w[i]+seg.back());
            }
        }
    }
    
    int pickIndex() {
        int res = rand()%seg.back();
        auto it = upper_bound(seg.begin(), seg.end(), res);
        return it-seg.begin();
    }
};

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

posted on 2022-09-02 17:43  Blackzxy  阅读(17)  评论(0编辑  收藏  举报