当前位置:网站首页>[leetcode daily question 2021/8/30]528. Choose randomly by weight [medium]
[leetcode daily question 2021/8/30]528. Choose randomly by weight [medium]
2022-07-26 10:40:00 【LittleSeedling】
528. Choose randomly by weight
The title comes from leetcode, Solutions and ideas represent only personal views . Portal .
difficulty : secondary
Time :30min
TAG: The prefix and , randomization
subject
Given an array of positive integers w , among w[i] Subscript subscript i The weight of ( Subscript from 0 Start ), Please write a function pickIndex , It can randomly take subscripts i, Select subscript i The probabilities of and w[i] In direct proportion to .
for example , about w = [1, 3], Select subscripts 0 The probability of is 1 / (1 + 3) = 0.25 ( namely ,25%), And choose subscript 1 The probability of is 3 / (1 + 3) = 0.75( namely ,75%).
in other words , Select subscript i The probability of is w[i] / sum(w) .
Example 1:
Input :
["Solution","pickIndex"]
[[[1]],[]]
Output :
[null,0]
explain :
Solution solution = new Solution([1]);
solution.pickIndex(); // return 0, Because there is only one element in the array , So the only option is to return the subscript 0.
Example 2:
Input :
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output :
[null,1,1,1,1,0]
explain :
Solution solution = new Solution([1, 3]);
solution.pickIndex(); // return 1, Returns the subscript 1, Return the subscript probability as 3/4 .
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0, Returns the subscript 0, Return the subscript probability as 1/4 .
Because it's a random problem , Allow multiple answers , So the following outputs can be considered correct :
[null,1,1,1,1,0]
[null,1,1,1,1,1]
[null,1,1,1,0,0]
[null,1,1,1,0,1]
[null,1,0,1,0,0]
......
and so on .
Tips :
- 1 <= w.length <= 10000
- 1 <= w[i] <= 105
- pickIndex Will be called no more than 10000 Time
Ideas
utilize w Calculation , Every index Should be selected 【 Probability array p】
Think about the key to solving this problem , It only needs When the number of calls is large enough , return index Probability of compliance 【 Probability array p】 that will do .
Every call changes , In the current situation ,index The probability of being selected . namely , In code nums An array with the total. utilize nums[index]/total, You can calculate , In the current situation ,index The probability of being selected .
What we need to do is , Maintain a nums Array , bring nums[i]/total Approximately equal to p[i].
Answer key
class Solution {
public:
vector<double> p;
double total = 0 + 1e-7;
vector<int> nums;
int n = 0;
Solution(vector<int>& w) {
int n = w.size();
this->n = n;
p.resize(n);
double sum = 0;
for(int i=0;i<n;i++){
sum += w[i];
}
for(int i=0;i<n;i++){
p[i] = w[i] / sum;
}
nums.resize(n);
}
int pickIndex() {
// Take a random number
int index = rand() % n;
while(nums[index]/total >= p[index]){
index = rand() % n;
}
nums[index]++;
total++;
return index;
}
};
/** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(w); * int param_1 = obj->pickIndex(); */
Algorithm complexity
Time complexity : Initialize array O ( n ) O(n) O(n), Each choice O ( ∑ i n w i ) O(\sum_i^n w_i) O(∑inwi).
Spatial complexity : O ( n ) O(n) O(n). Probability array p, Count array nums.

The time to initialize the array is easy to calculate , Time selected each time , My thoughts are as follows .
nums = [1,1,1], total = 3, w=[2,2,2], p=[1/3,1/3,1/3]
at present ,nums[i]/total Is in accordance with p[i] Of .
that , With total An increase in , The next time nums[i]/total accord with p[i] when ,total The smallest case is ?
Should be nums = [2,2,2], That is, everyone increases 1 individual .total increase 3.
Then if ,
nums = [1,2,1], total = 4, w=[1,2,1], p=[1/4,1/2,1/4]
that , With total An increase in , The next time nums[i]/total accord with p[i] when ,total The smallest case is ?
Should be nums = [2,4,2], That is to say total increase 4.
Then if ,
nums = [2,4,2], total = 8, w=[1,2,1], p=[1/4,1/2,1/4]
that , With total An increase in , The next time nums[i]/total accord with p[i] when ,total The smallest case is ?
Should be nums = [3,6,9], instead of nums = [4,8,4],total increase 4.
Then if ,
nums = [1,2,1], total = 4, w=[2,4,2], p=[1/4,1/2,1/4]
that , With total An increase in , The next time nums[i]/total accord with p[i] when ,total The smallest case is ?
Should be nums = [2,4,2], instead of nums = [3,6,9], That is to say total increase 4, instead of 8.
therefore , In each sampling , Each time it reaches the next state (nums[i]/total accord with p[i]),total It should increase ( Less than ) ∑ i n w i \sum_i^n w_i ∑inwi Time .
Why less than ?
because ,total What should be added is ,w Zhongba Common divisor The accumulated value after reduction .
边栏推荐
- Asynctask < T> decoration and await are not used in synchronous methods to obtain asynchronous return values (asynchronous methods are called in synchronous methods)
- .NET操作Redis Hash对象
- GIS方法类期刊和论文的综述(Introduction)怎么写?
- [Halcon vision] Fourier transform of image
- .net operation redis list list
- hx711 数据波动大的问题
- 头歌 Phoenix 入门(第1关:Phoenix 安装、第2关:Phoenix 基础语法)
- algorithm
- [leetcode每日一题2021/2/14]765. 情侣牵手
- Redis特殊数据类型使用场景
猜你喜欢

工厂模式详解

Tradingview tutorial

Navicat15 MySQL (centos7) connected to local virtual machine

第6期:大学生应该选择哪种主流编程语言
![[machine learning notes] [face recognition] deeplearning ai course4 4th week programming](/img/7e/9c0e88097b90c0c24ebf86f090805b.png)
[machine learning notes] [face recognition] deeplearning ai course4 4th week programming
![[machine learning notes] [style transfer] deeplearning ai course4 4th week programming(tensorflow2)](/img/94/ff52b043320b6dea5ca1238e314de8.png)
[machine learning notes] [style transfer] deeplearning ai course4 4th week programming(tensorflow2)

RT-Thread 学习笔记(七)---开启基于SPI Flash的elmfat文件系统(中)

vscode上使用anaconda(已经配置好环境)

20210807#1 C语言程序结构

Application of.Net open source framework in industrial production
随机推荐
.net operation redis sorted set ordered set
分布式锁解决方案之Redis实现
2021-08-12函数递归_和鹏哥学习C语言
使用Geoprocessor 工具
Uninstall Meizu app store
SAP ABAP 守护进程的实现方式
Centos8 (liunx) deploying WTM (asp.net 5) using PgSQL
Some web APIs you don't know
[machine learning notes] [style transfer] deeplearning ai course4 4th week programming(tensorflow2)
剑指Offer(四十四):翻转单词顺序序列
MLX90640 红外热成像仪测温传感器模块开发笔记(六)红外图像伪彩色编码
Mlx90640 infrared thermal imager temperature sensor module development notes (VI) pseudo color coding of infrared images
Application of.Net open source framework in industrial production
[Halcon vision] Fourier transform of image
剑指Offer(五):用两个栈实现队列
MD5加密
C语言计算日期间隔天数
[notes on machine learning] [building a cyclic neural network and its application] deeplearning ai course5 1st week programming(keras)
[leetcode每日一题2021/4/23]368. 最大整除子集
抽象工厂及其改进示例