Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
random-flip-matrix.cpp 1.03 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-07-29 02:29 +08:00 . Update random-flip-matrix.cpp
// Time: ctor: O(1)
// flip: O(1)
// reset: O(min(f, r * c))
// Space: O(min(f, r * c))
class Solution {
public:
Solution(int n_rows, int n_cols) :
n_rows_(n_rows),
n_cols_(n_cols),
n_(n_rows * n_cols),
gen_{(random_device())()} {
}
vector<int> flip() {
uniform_int_distribution<int> uni(0, --n_);
const auto target = uni(gen_);
int x = get(target, target);
lookup_[target] = get(n_, n_);
return {x / n_cols_, x % n_cols_};
}
void reset() {
lookup_.clear();
n_ = n_rows_ * n_cols_;
}
private:
int get(int key, int default_value) {
return lookup_.count(key) ? lookup_[key] : default_value;
}
int n_rows_;
int n_cols_;
int n_;
unordered_map<int, int> lookup_;
default_random_engine gen_;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(n_rows, n_cols);
* vector<int> param_1 = obj.flip();
* obj.reset();
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助