You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: leetcode/binary-search/528-random-pick-with-weight.md
+35-3Lines changed: 35 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@
4
4
5
5
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.
6
6
7
-
**Note:
7
+
**Note:
8
8
**
9
9
10
10
1. 1 <= w.length <= 10000
@@ -29,7 +29,7 @@ Input:
29
29
Output: [null,0,1,1,1,0]
30
30
```
31
31
32
-
**Explanation of Input Syntax:
32
+
**Explanation of Input Syntax:
33
33
**
34
34
35
35
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
43
43
4. Time complexity O\(n\)
44
44
5. Space complexity O\(n\)
45
45
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\)
47
50
3. asd
48
51
49
52
### Solution
@@ -77,6 +80,35 @@ class Solution {
77
80
*/
78
81
```
79
82
83
+
```java
84
+
classSolution {
85
+
privateTreeMap<Integer, Integer> map;
86
+
privateRandom rand;
87
+
privateint total;
88
+
89
+
publicSolution(int[] w) {
90
+
map =newTreeMap<>();
91
+
total =0;
92
+
rand =newRandom();
93
+
for (int i =0; i < w.length; i++) {
94
+
total += w[i];
95
+
map.put(total, i);
96
+
}
97
+
}
98
+
99
+
publicintpickIndex() {
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:
0 commit comments