当前位置:网站首页>[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 .
边栏推荐
猜你喜欢

【机器学习小记】【风格迁移】deeplearning.ai course4 4th week programming(tensorflow2)

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

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

异常的概念与处理

Application of.Net open source framework in industrial production

GIS方法类期刊和论文的综述(Introduction)怎么写?

英语基础句型结构------起源
![[leetcode每日一题2021/2/14]765. 情侣牵手](/img/be/8639a05c733638bf0b3fdeb11abccf.png)
[leetcode每日一题2021/2/14]765. 情侣牵手

Phase 4: one of College Students' vocational skills preparation in advance

从蚂蚁的觅食过程看团队研发(转载)
随机推荐
文案秘籍七步曲至----文献团队协作管理
C语言鹏哥20210812C语言函数
7-25 0-1背包 (50分)
Dry goods likeshop takeout order system is open source, 100% open source, no encryption
Application of.Net open source framework in industrial production
The problem of large fluctuation of hx711 data
Interview questions and answers of the first company (I)
.NET操作Redis sorted set有序集合
uniapp使用简单方法signalR(仅用于web调试,无法打包app)
异常的概念与处理
.NET操作Redis Set无序集合
datav漂亮数据屏制作体验
粽子大战 —— 猜猜谁能赢
11 在 operator= 中处理“自我赋值”
Analysis of the transaction problem of chained method call
10 令 operator= 返回一个 reference to *this
Uniapp uses the simple method signalr (only for web debugging, cannot package apps)
数据分析入门 | kaggle泰坦尼克任务(一)—>数据加载和初步观察
12 复制对象时勿忘其每一个成分
Inheritance method of simplified constructor (II) - class inheritance in ES6