Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 0c1dbc8

Browse filesBrowse files
Add files via upload
1 parent 086c638 commit 0c1dbc8
Copy full SHA for 0c1dbc8

File tree

1 file changed

+43
-0
lines changed
Filter options

1 file changed

+43
-0
lines changed
+43Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// 基本思路是使用二分查找
2+
3+
// Runtime: 148 ms, faster than 43.79% of C++ online submissions for Random Pick with Weight.
4+
// Memory Usage: 32.9 MB, less than 40.00% of C++ online submissions for Random Pick with Weight.
5+
6+
class Solution
7+
{
8+
public:
9+
Solution(vector<int>& w)
10+
{
11+
for (int num : w)
12+
{
13+
sum += num;
14+
weights.push_back(sum);
15+
}
16+
}
17+
18+
int pickIndex()
19+
{
20+
int pos = random() % sum;
21+
22+
int leftPtr = 0, rightPtr = weights.size() - 1;
23+
24+
while (leftPtr < rightPtr)
25+
{
26+
int mid = (leftPtr + rightPtr) / 2;
27+
28+
if (weights[mid] > pos) rightPtr = mid;
29+
else leftPtr = mid + 1;
30+
}
31+
32+
return leftPtr;
33+
}
34+
private:
35+
int sum = 0;
36+
vector<int> weights;
37+
};
38+
39+
/**
40+
* Your Solution object will be instantiated and called as such:
41+
* Solution* obj = new Solution(w);
42+
* int param_1 = obj->pickIndex();
43+
*/

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.