File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments