We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f835976 commit ca18057Copy full SHA for ca18057
Design/528_Random_Pick_with_Weight.java
@@ -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