Advertisement
nikunjsoni

528

May 13th, 2021
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.62 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> prefixSum;
  4.     Solution(vector<int>& w) {
  5.         prefixSum.assign(w.size(), 0);
  6.         for(int i=0; i<w.size(); i++){
  7.             prefixSum[i] = w[i] + ((i>0) ? prefixSum[i-1] : 0);
  8.         }
  9.     }
  10.    
  11.     int pickIndex() {
  12.         float randNum = float(rand()) / RAND_MAX;
  13.         float target = randNum * prefixSum.back();
  14.         return upper_bound(prefixSum.begin(), prefixSum.end(), target)-prefixSum.begin();
  15.     }
  16. };
  17.  
  18. /**
  19.  * Your Solution object will be instantiated and called as such:
  20.  * Solution* obj = new Solution(w);
  21.  * int param_1 = obj->pickIndex();
  22.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement