Skip to content

Commit 5dd2f8d

Browse files
committed
Runtime 682 ms (Top 6.58%) | Memory 55.0 MB (Top 5.92%)
1 parent 0793048 commit 5dd2f8d

File tree

1 file changed

+31
-20
lines changed

1 file changed

+31
-20
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,34 @@
1-
var Solution = function(w) {
2-
this.w = [];
3-
this.total = w.reduce((collector, el)=>collector+el,0)
4-
let start = 0
5-
for (const el of w){
6-
this.w.push([start, start+el])
7-
start = start+el
1+
class Solution {
2+
constructor(nums) {
3+
this.map = new Map();
4+
this.sum = 0;
5+
6+
nums.forEach((num, i) => {
7+
this.sum += num;
8+
this.map.set(this.sum, i);
9+
})
810
}
9-
};
10-
11-
/**
12-
* @return {number}
13-
*/
14-
Solution.prototype.pickIndex = function() {
15-
const rand = Math.floor(Math.random()*this.total)
16-
for (let i = 0; i < this.w.length ; i++){
17-
const pair = this.w[i];
18-
if (pair[0] <= rand && rand < pair[1]){
19-
return i;
11+
pickIndex = function() {
12+
const random_sum = Math.floor(Math.random() * this.sum);
13+
return this.fetchIndexUsingBS(random_sum);
14+
}
15+
fetchIndexUsingBS = function(target) {
16+
const sums = Array.from(this.map.keys());
17+
let lo = 0,
18+
hi = sums.length - 1,
19+
mid;
20+
21+
while(lo <= hi) {
22+
mid = Math.floor((hi - lo)/2) + lo;
23+
// if((mid === 0 || sums[mid - 1] < target) && sums[mid] >= target) {
24+
// return this.map.get(sums[mid]);
25+
// }
26+
if(sums[mid] > target) {
27+
hi = mid - 1;
28+
} else {
29+
lo = mid + 1;
30+
}
2031
}
32+
return lo;
2133
}
22-
23-
};
34+
}

0 commit comments

Comments
 (0)