Skip to content

Commit ca18057

Browse files
committed
Add 528_Random_Pick_with_Weight.java
1 parent f835976 commit ca18057

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
int[] prefix;
3+
int totalSum;
4+
5+
public Solution(int[] w) {
6+
prefix = new int[w.length];
7+
8+
for (int i = 0; i < w.length; i++) {
9+
totalSum += w[i];
10+
prefix[i] = totalSum;
11+
}
12+
}
13+
14+
public int pickIndex() {
15+
int low = 0, high = prefix.length - 1;
16+
double target = totalSum * Math.random();
17+
18+
while (low < high) {
19+
int mid = low + (high - low) / 2;
20+
21+
if (prefix[mid] < target) {
22+
low = mid + 1;
23+
} else {
24+
high = mid;
25+
}
26+
}
27+
28+
return low;
29+
}
30+
}

0 commit comments

Comments
 (0)