A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 528. Random Pick with Weight, the solution in this repository is mainly a binary search solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: binary search, two pointers, sliding window.
The notes already sitting in the source point us in the right direction:
- http://www.cplusplus.com/reference/random/discrete_distribution/
- https://stackoverflow.com/questions/1761626/weighted-random-numbers
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are pickIndex.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//http://www.cplusplus.com/reference/random/discrete_distribution/
02//https://stackoverflow.com/questions/1761626/weighted-random-numbers
03//Runtime: 188 ms, faster than 50.33% of C++ online submissions for Random Pick with Weight.
04//Memory Usage: 42 MB, less than 5.06% of C++ online submissions for Random Pick with Weight.
05class Solution {
06public:
07 vector<int> w;
08 std::discrete_distribution<int> dist;;
09 std::mt19937 gen;
10
11 Solution(vector<int>& w) {
12 this->w = w;
13 this->dist = std::discrete_distribution<int>(std::begin(w), std::end(w));
14 // this->gen.seed(time(0));//if you want different results from different runs
15 }
16
17 int pickIndex() {
18 //cannot initialize dist and gen here!!
19 return dist(gen);
20 }
21};
22
23/**
24 * Your Solution object will be instantiated and called as such:
25 * Solution* obj = new Solution(w);
26 * int param_1 = obj->pickIndex();
27 */
28
29//binary search
30//https://leetcode.com/problems/random-pick-with-weight/discuss/154044/Java-accumulated-freq-sum-and-binary-search
31//Runtime: 180 ms, faster than 64.49% of C++ online submissions for Random Pick with Weight.
32//Memory Usage: 40.6 MB, less than 34.54% of C++ online submissions for Random Pick with Weight.
33class Solution {
34public:
35 //accumulated sum
36 vector<int> acc;
37
38 Solution(vector<int>& w) {
39 this->acc = w;
40 for(int i = 1; i < this->acc.size(); i++){
41 this->acc[i] += this->acc[i-1];
42 }
43 /*
44 for w = [1, 4, 2],
45 we have acc = [1, 5, 7],
46 this represents 3 groups: [1], [2...4], [5...7]
47
48 we will random generate a number in the range [1,7],
49 and then assign it to one of the groups above,
50 for example if w generate idx = 3,
51 we will assign it to the group [2...4](4 is just above 3),
52 and then get the group's index as answer
53 */
54 }
55
56 int pickIndex() {
57 //a number in the range [1...acc[acc.size()-1]]
58 int num = rand()%acc[acc.size()-1]+1;
59
60 /*
61 binary search to find the index left or mid
62 s.t. acc[left] > num or acc[mid] == num
63
64 i.e. find left boundary
65 */
66
67 int left = 0, right = acc.size()-1;
68
69 while(left <= right){
70 int mid = left + (right-left)/2;
71
72 if(num == acc[mid]){
73 return mid;
74 }else if(num < acc[mid]){
75 right = mid-1;
76 }else/* if(num > acc[mid])*/{
77 left = mid+1;
78 }
79 }
80
81 return left;
82 }
83};
84
85/**
86 * Your Solution object will be instantiated and called as such:
87 * Solution* obj = new Solution(w);
88 * int param_1 = obj->pickIndex();
89 */
Cost