Given an array
w
of positive integers, wherew[i]
describes the weight of indexi
, write a functionpickIndex
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.
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments.Solution
's constructor has one argument, the arrayw
.pickIndex
has no arguments. Arguments are always wrapped with a list, even if there aren't any.
給予一正整數陣列
w
,其中w[i]
描述索引為i
的權重。寫一個函式pickIndex
會按照權重去隨機挑選一個索引。
注意:
1 <= w.length <= 10000
1 <= w[i] <= 10^5
pickIndex
至少會被呼叫10000
次。
輸入語法解釋:
輸入會是兩個列表:哪些副程式被呼叫和它們的參數。
Solution
的建構子有一個參數:陣列w
。pickIndex
沒有參數。參數總是被包裝在列表中,即便沒有任何參數。
rand()
可以得到一個隨機值,介於0
到int的最大值。vector
去儲存它;並將元素改為遞增。
[1, 2, 3]
,新的vector
為[1, 3, 6]
。rand() % sum(w)
,可以得到一個0 ~ sum(w)
的數字。vector
的哪個區間,就代表選到哪個數字。
LeetCode
C++