Skip to content

Commit 43b0822

Browse files
committed
Add solution #528
1 parent e296fe6 commit 43b0822

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,7 @@
423423
524|[Longest Word in Dictionary through Deleting](./0524-longest-word-in-dictionary-through-deleting.js)|Medium|
424424
525|[Contiguous Array](./0525-contiguous-array.js)|Medium|
425425
526|[Beautiful Arrangement](./0526-beautiful-arrangement.js)|Medium|
426+
528|[Random Pick with Weight](./0528-random-pick-with-weight.js)|Medium|
426427
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
427428
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
428429
542|[01 Matrix](./0542-01-matrix.js)|Medium|
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 528. Random Pick with Weight
3+
* https://leetcode.com/problems/random-pick-with-weight/
4+
* Difficulty: Medium
5+
*
6+
* You are given a 0-indexed array of positive integers w where w[i] describes the
7+
* weight of the ith index.
8+
*
9+
* You need to implement the function pickIndex(), which randomly picks an index in
10+
* the range [0, w.length - 1] (inclusive) and returns it. The probability of picking
11+
* an index i is w[i] / sum(w).
12+
*
13+
* For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25
14+
* (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).
15+
*/
16+
17+
/**
18+
* @param {number[]} w
19+
*/
20+
var Solution = function(w) {
21+
this.sums = [];
22+
let sum = 0;
23+
for (const weight of w) {
24+
sum += weight;
25+
this.sums.push(sum);
26+
}
27+
this.total = sum;
28+
};
29+
30+
/**
31+
* @return {number}
32+
*/
33+
Solution.prototype.pickIndex = function() {
34+
const target = Math.random() * this.total;
35+
let left = 0;
36+
let right = this.sums.length - 1;
37+
while (left < right) {
38+
const mid = Math.floor((left + right) / 2);
39+
if (this.sums[mid] <= target) {
40+
left = mid + 1;
41+
} else {
42+
right = mid;
43+
}
44+
}
45+
return left;
46+
};

0 commit comments

Comments
 (0)