[LeetCode] Random Pick with Weight 根据权重随机取点
Given an array w
of positive integers, where w[i]
describes the weight of index i
, write a function pickIndex
which randomly picks an index in proportion to its weight.
Note:
1 <= w.length <= 10000
1 <= w[i] <= 10^5
pickIndex
will be called at most10000
times.
Example 1:
Input:
["Solution","pickIndex"]
[[[1]],[]]
Output: [null,0]
Example 2:
Input:
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output: [null,0,1,1,1,0]
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution
's constructor has one argument, the array w
. pickIndex
has no arguments. Arguments are always wrapped with a list, even if there aren't any.
这道题给了一个权重数组,让我们根据权重来随机取点,现在的点就不是随机等概率的选取了,而是要根据权重的不同来区别选取。比如题目中例子2,权重为 [1, 3],表示有两个点,权重分别为1和3,那么就是说一个点的出现概率是四分之一,另一个出现的概率是四分之三。由于我们的rand()函数是等概率的随机,那么我们如何才能有权重的随机呢,我们可以使用一个trick,由于权重是1和3,相加为4,那么我们现在假设有4个点,然后随机等概率取一个点,随机到第一个点后就表示原来的第一个点,随机到后三个点就表示原来的第二个点,这样就可以保证有权重的随机啦。那么我们就可以建立权重数组的累加和数组,比如若权重数组为 [1, 3, 2] 的话,那么累加和数组为 [1, 4, 6],整个的权重和为6,我们 rand() % 6,可以随机出范围 [0, 5] 内的数,随机到 0 则为第一个点,随机到 1,2,3 则为第二个点,随机到 4,5 则为第三个点,所以我们随机出一个数字x后,然后再累加和数组中查找第一个大于随机数x的数字,使用二分查找法可以找到第一个大于随机数x的数字的坐标,即为所求,参见代码如下:
解法一:
class Solution {
public:
Solution(vector<int> w) {
sum = w;
for (int i = ; i < w.size(); ++i) {
sum[i] = sum[i - ] + w[i];
}
} int pickIndex() {
int x = rand() % sum.back(), left = , right = sum.size() - ;
while (left < right) {
int mid = left + (right - left) / ;
if (sum[mid] <= x) left = mid + ;
else right = mid;
}
return right;
} private:
vector<int> sum;
};
我们也可以把二分查找法换为STL内置的upper_bound函数,根据上面的分析,我们随机出一个数字x后,然后再累加和数组中查找第一个大于随机数x的数字,使用二分查找法可以找到第一个大于随机数x的数字的坐标。而upper_bound() 函数刚好就是查找第一个大于目标值的数,lower_bound() 函数是找到第一个不小于目标值的数,用在这里就不太合适了,关于二分搜索发的分类可以参见博主之前的博客LeetCode Binary Search Summary 二分搜索法小结,参见代码如下:
解法二:
class Solution {
public:
Solution(vector<int> w) {
sum = w;
for (int i = ; i < w.size(); ++i) {
sum[i] = sum[i - ] + w[i];
}
} int pickIndex() {
int x = rand() % sum.back();
return upper_bound(sum.begin(), sum.end(), x) - sum.begin();
} private:
vector<int> sum;
};
讨论:这题有个很好的follow up,就是说当weights数组经常变换怎么办,那么这就有涉及到求变化的区域和问题了,在博主之前的一道 Range Sum Query - Mutable 中有各种方法详细的讲解。只要把两道题的解法的精髓融合到一起就行了,可以参见论坛上的这个帖子。
类似题目:
Random Point in Non-overlapping Rectangles
参考资料:
https://leetcode.com/problems/random-pick-with-weight/discuss/154024/JAVA-8-lines-TreeMap
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Random Pick with Weight 根据权重随机取点的更多相关文章
- [leetcode]528. Random Pick with Weight按权重挑选索引
Given an array w of positive integers, where w[i] describes the weight of index i, write a function ...
- 528. Random Pick with Weight index的随机发生器
[抄题]: Given an array w of positive integers, where w[i] describes the weight of index i, write a fun ...
- select random item with weight 根据权重随机选出
http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/ 类似俄罗斯轮盘赌
- [LeetCode] Random Pick with Blacklist 带黑名单的随机选取
Given a blacklist B containing unique integers from [0, N), write a function to return a uniform ran ...
- LeetCode 528. Random Pick with Weight
原题链接在这里:https://leetcode.com/problems/random-pick-with-weight/ 题目: Given an array w of positive inte ...
- 528. Random Pick with Weight
1. 问题 给定一个权重数组w,w[i]表示下标i的权重,根据权重从数组中随机抽取下标. 2. 思路 这道题相当于 497. Random Point in Non-overlapping Recta ...
- [Swift]LeetCode528. 按权重随机选择 | Random Pick with Weight
Given an array w of positive integers, where w[i] describes the weight of index i, write a function ...
- 【LeetCode】528. Random Pick with Weight 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/random-pi ...
- [LeetCode] Random Pick Index 随机拾取序列
Given an array of integers with possible duplicates, randomly output the index of a given target num ...
随机推荐
- WPF布局的应用
一 写在开头1.1 本文内容本文主要内容是使用WPF来实现几个简单的界面. 二 登录窗口小例子2.1 实现代码XAML代码: <Window x:Class="LoginDialog. ...
- 多人聊天室(Java)
第1部分 TCP和UDP TCP:是一种可靠地传输协议,是把消息按一个个小包传递并确认消息接收成功和正确才发送下一个包,速度相对于UDP慢,但是信息准确安全:常用于一般不要求速度和需要准确发送消息的场 ...
- C#VS2017添加ReportViewer控件
安装完vs2017之后我们进行添加Report Viewer控件: 1. 点击Tools -> Extensions and Updates... 2. 在新窗口搜索栏中输入rdlc后搜索,结果 ...
- 【原创】大数据基础之ElasticSearch(2)常用API整理
Fortunately, Elasticsearch provides a very comprehensive and powerful REST API that you can use to i ...
- 【原创】Linux基础之用户和组
1 添加.删除用户 # useradd $user# userdel $user 2 设置用户密码 # passwd $user /etc/passwd 3 查看$user的用户和组信息 # id $ ...
- 【原创】大叔问题定位分享(28)openssh升级到7.4之后ssh跳转异常
服务器集群之间忽然ssh跳转不通 # ssh 192.168.0.1The authenticity of host '192.168.0.1 (192.168.0.1)' can't be esta ...
- form表单获取多选的值
flask 中 form 表单直接获取多选框的值时 language = request.values.getlist('values')或 language=request.from.getlist ...
- Hibernate Envers
一.目的Hibernate Envers的目的是提供应用程序实体数据的历史版本,记录执行数据变更历史. 二.用途Hibernate Envers记录的审计数据,主要用于意外丢失数据找回.审查数据合法性 ...
- 关于在windows上远行的虚拟机为ubuntu16.04中不能复制和粘贴的问题解决方案
Linux安装 VMware tools 工具解决复制和粘贴的方法 VMware虚拟机中如何安装VMWare-Tools详解好处:可以支持图形界面,可以支持共享文件功能等 1 工具/原料 1)安装过虚 ...
- python之基于libsvm识别数字验证码
1. 参考 字符型图片验证码识别完整过程及Python实现 2.图片预处理和手动分类 (1)分析图片 from PIL import Image img = Image.open('nums/ttt. ...