|
| 1 | +// Time: O(logn) |
| 2 | +// Space: O(n) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + Solution(vector<vector<int>> rects) : |
| 7 | + rects_(move(rects)), |
| 8 | + gen_{(random_device())()} { |
| 9 | + |
| 10 | + for (const auto& rect : rects_) { |
| 11 | + const auto width = rect[2] - rect[0] + 1; |
| 12 | + const auto height = rect[3] - rect[1] + 1; |
| 13 | + if (prefix_sum_.empty()) { |
| 14 | + prefix_sum_.emplace_back(width * height); |
| 15 | + } else { |
| 16 | + prefix_sum_.emplace_back(prefix_sum_.back() + width * height); |
| 17 | + } |
| 18 | + } |
| 19 | + uni_ = uniform_int_distribution<int>{0, prefix_sum_.back() - 1}; |
| 20 | + } |
| 21 | + |
| 22 | + vector<int> pick() { |
| 23 | + const auto target = uni_(gen_); |
| 24 | + const auto left = distance(prefix_sum_.cbegin(), |
| 25 | + upper_bound(prefix_sum_.cbegin(), |
| 26 | + prefix_sum_.cend(), |
| 27 | + target)); |
| 28 | + const auto& rect = rects_[left]; |
| 29 | + const auto width = rect[2] - rect[0] + 1; |
| 30 | + const auto height = rect[3] - rect[1] + 1; |
| 31 | + const auto base = prefix_sum_[left] - width * height; |
| 32 | + return {rect[0] + (target - base) % width, rect[1] + (target - base) / width}; |
| 33 | + } |
| 34 | + |
| 35 | +private: |
| 36 | + const vector<vector<int>> rects_; |
| 37 | + vector<int> prefix_sum_; |
| 38 | + default_random_engine gen_; |
| 39 | + uniform_int_distribution<int> uni_; |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * Your Solution object will be instantiated and called as such: |
| 44 | + * Solution obj = new Solution(rects); |
| 45 | + * vector<int> param_1 = obj.pick(); |
| 46 | + */ |
| 47 | + |
0 commit comments