-
Notifications
You must be signed in to change notification settings - Fork 115
/
0528-RandomPickWithWeight.cs
52 lines (45 loc) · 1.39 KB
/
0528-RandomPickWithWeight.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//-----------------------------------------------------------------------------
// Runtime: 208ms
// Memory Usage: 47.4 MB
// Link: https://leetcode.com/submissions/detail/379087578/
//-----------------------------------------------------------------------------
using System;
namespace LeetCode
{
public class _0528_RandomPickWithWeight
{
private readonly int[] prefixSums;
private readonly int totalSum;
private readonly Random random;
public _0528_RandomPickWithWeight(int[] w)
{
prefixSums = new int[w.Length];
for (int i = 0; i < w.Length; i++)
{
totalSum += w[i];
prefixSums[i] = totalSum;
}
random = new Random();
}
public int PickIndex()
{
var target = random.Next(totalSum) + 1;
int lo = 0, hi = prefixSums.Length - 1;
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (target == prefixSums[mid]) return mid;
if (target > prefixSums[mid])
lo = mid + 1;
else
hi = mid - 1;
}
return lo;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(w);
* int param_1 = obj.PickIndex();
*/
}