forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_528.java
37 lines (33 loc) · 981 Bytes
/
_528.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.fishercoder.solutions;
import java.util.Random;
public class _528 {
public static class Solution1 {
Random random;
int[] preSums;
public Solution1(int[] w) {
this.random = new Random();
for (int i = 1; i < w.length; ++i) {
w[i] += w[i - 1];
}
this.preSums = w;
}
public int pickIndex() {
int len = preSums.length;
int idx = random.nextInt(preSums[len - 1]) + 1;
int left = 0;
int right = len - 1;
// search position
while (left < right) {
int mid = left + (right - left) / 2;
if (preSums[mid] == idx) {
return mid;
} else if (preSums[mid] < idx) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}
}