码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 528 按权重随机选择

时间:2021-06-04 18:57:54      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:tco   lang   lan   java   while   简单   psu   target   函数   

简介

记住如何使用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 按权重随机选择

标签:tco   lang   lan   java   while   简单   psu   target   函数   

原文地址:https://www.cnblogs.com/eat-too-much/p/14847365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!