We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 7b0ed06 commit 2b3c216Copy full SHA for 2b3c216
scripts/algorithms/R/Random Pick with Weight/Random Pick with Weight.java
@@ -1,5 +1,6 @@
1
+// Runtime: 50 ms (Top 42.43%) | Memory: 56.3 MB (Top 78.21%)
2
class Solution {
-
3
+
4
private int[] prefixSum;
5
private Random random;
6
@@ -9,21 +10,21 @@ public Solution(int[] w) {
9
10
prefixSum = w;
11
random = new Random();
12
}
13
14
public int pickIndex() {
15
int num = 1 + random.nextInt(prefixSum[prefixSum.length - 1]); // Generate random number between 1 and total sum of weights
16
int left = 0;
17
int right = prefixSum.length - 1;
18
19
while (left < right) {
20
int mid = (left + right) / 2;
21
if (num == prefixSum[mid])
22
return mid;
- else if (num < prefixSum[mid])
23
+ else if (num < prefixSum[mid])
24
right = mid;
25
else
26
left = mid + 1;
27
28
return left;
29
-}
30
+}
0 commit comments