Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
random-point-in-non-overlapping-rectangles.cpp 1.53 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-07-29 02:31 +08:00 . Update random-point-in-non-overlapping-rectangles.cpp
// Time: ctor: O(n)
// pick: O(logn)
// Space: O(n)
class Solution {
public:
Solution(vector<vector<int>> rects) :
rects_(move(rects)),
gen_{(random_device())()} {
for (const auto& rect : rects_) {
const auto width = rect[2] - rect[0] + 1;
const auto height = rect[3] - rect[1] + 1;
if (prefix_sum_.empty()) {
prefix_sum_.emplace_back(width * height);
} else {
prefix_sum_.emplace_back(prefix_sum_.back() + width * height);
}
}
uni_ = uniform_int_distribution<int>{0, prefix_sum_.back() - 1};
}
vector<int> pick() {
const auto target = uni_(gen_);
const auto left = distance(prefix_sum_.cbegin(),
upper_bound(prefix_sum_.cbegin(),
prefix_sum_.cend(),
target));
const auto& rect = rects_[left];
const auto width = rect[2] - rect[0] + 1;
const auto height = rect[3] - rect[1] + 1;
const auto base = prefix_sum_[left] - width * height;
return {rect[0] + (target - base) % width, rect[1] + (target - base) / width};
}
private:
const vector<vector<int>> rects_;
vector<int> prefix_sum_;
default_random_engine gen_;
uniform_int_distribution<int> uni_;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(rects);
* vector<int> param_1 = obj.pick();
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助