还需要进一步理解
Solution1:
class Solution {
Random rand;
int[] a;
public Solution(int[] w) {
this.rand = new Random();
this.a = new int[w.length];
a[0] = w[0];
for(int i = 1; i<a.length; i++) {
a[i] = a[i-1] + w[i];
}
}
public int pickIndex() {
int guess = rand.nextInt(a[a.length-1]) + 1;
// embedded binary search
int pos = Arrays.binarySearch(a, guess);
if (pos<0) {
pos = -(pos+1);
}
return pos;
}
}
Solution2:
自己写的binary search
class Solution {
Random rand;
int[] a;
public Solution(int[] w) {
this.rand = new Random();
this.a = new int[w.length];
a[0] = w[0];
for(int i = 1; i<a.length; i++) {
a[i] = a[i-1] + w[i];
}
}
public int pickIndex() {
int guess = rand.nextInt(a[a.length-1]) + 1;
int pos = binarySearch(guess, a);
if (pos<0) {
pos = -1 * (pos+1);
}
return pos;
}
public int binarySearch(int guess, int[] a) {
int l = 0;
int r = a.length-1;
while (l<r) {
int mid = (l+r)/2;
if (a[mid] < guess) {
l = mid+1;
} else {
r = mid;
}
}
return r;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(w);
* int param_1 = obj.pickIndex();
*/