leetcode 528 按权重随机选择

Posted 小师叔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 528 按权重随机选择相关的知识,希望对你有一定的参考价值。

简介

记住如何使用C++11函数的话会很简单.

参考链接

https://leetcode-cn.com/problems/random-pick-with-weight/solution/528-an-quan-zhong-sui-ji-xuan-ze-qian-zh-p54t/

code

class Solution {
public:
    vector<int> presum;

    // 求前缀和
    Solution(vector<int>& w): presum(move(w)) {
        partial_sum(presum.begin(), presum.end(), presum.begin());
    }
    
    int pickIndex() {
        int pos = (rand() % presum.back()) + 1;
        return lower_bound(presum.begin(), presum.end(), pos) - presum.begin();
    }  
};
class Solution {

    List<Integer> psum = new ArrayList<>();
    int tot = 0;
    Random rand = new Random();

    public Solution(int[] w) {
        for (int x : w) {
            tot += x;
            psum.add(tot);
        }
    }

    public int pickIndex() {
        int targ = rand.nextInt(tot);

        int lo = 0;
        int hi = psum.size() - 1;
        while (lo != hi) {
            int mid = (lo + hi) / 2;
            if (targ >= psum.get(mid)) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }
}


以上是关于leetcode 528 按权重随机选择的主要内容,如果未能解决你的问题,请参考以下文章

按权重随机选择(leetcode 528)

按权重随机选择(leetcode 528)

LeetCode 1480. 一维数组的动态和 / 1588. 所有奇数长度子数组的和 / 528. 按权重随机选择(随机化)

[528]. 按权重随机选择

[528]. 按权重随机选择

528. 按权重随机选择