Skip to content

Commit 9789965

Browse files
committed
Updates leetcode/binary-search/528-random-pick-with-weight.md
Auto commit by GitBook Editor
1 parent 3c962e9 commit 9789965

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

leetcode/binary-search/528-random-pick-with-weight.md

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
Given an array w of positive integers, where w\[i\] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.
66

7-
**Note:
7+
**Note:
88
**
99

1010
1. 1 <= w.length <= 10000
@@ -29,7 +29,7 @@ Input:
2929
Output: [null,0,1,1,1,0]
3030
```
3131

32-
**Explanation of Input Syntax:
32+
**Explanation of Input Syntax:
3333
**
3434

3535
The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the array w. pickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any.
@@ -43,7 +43,10 @@ The input is two lists: the subroutines called and their arguments. Solution's c
4343
4. Time complexity O\(n\)
4444
5. Space complexity O\(n\)
4545
2. TreeMap
46-
1.
46+
1. We can leverage the treemap built-in treemap to do similar thing as above
47+
2. Save the accumulated sum and its index, we can retrieve the index latter
48+
3. Time complexity O\(n\)
49+
4. Space complexity O\(n\)
4750
3. asd
4851

4952
### Solution
@@ -77,6 +80,35 @@ class Solution {
7780
*/
7881
```
7982

83+
```java
84+
class Solution {
85+
private TreeMap<Integer, Integer> map;
86+
private Random rand;
87+
private int total;
88+
89+
public Solution(int[] w) {
90+
map = new TreeMap<>();
91+
total = 0;
92+
rand = new Random();
93+
for (int i = 0; i < w.length; i++) {
94+
total += w[i];
95+
map.put(total, i);
96+
}
97+
}
98+
99+
public int pickIndex() {
100+
int k = map.higherKey(rand.nextInt(total));
101+
return map.get(k);
102+
}
103+
}
104+
105+
/**
106+
* Your Solution object will be instantiated and called as such:
107+
* Solution obj = new Solution(w);
108+
* int param_1 = obj.pickIndex();
109+
*/
110+
```
111+
80112
### Additional {#additional}
81113

82114

0 commit comments

Comments
 (0)