Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
implement-rand10-using-rand7.cpp 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-07-26 00:37 +08:00 . Update implement-rand10-using-rand7.cpp
// Time: O(1.199), counted by statistics, limit would be O(log10/log7) = O(1.183)
// Space: O(1)
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
// Reference: https://leetcode.com/problems/implement-rand10-using-rand7/discuss/151567/C++JavaPython-Average-1.199-Call-rand7-Per-rand10
class Solution {
public:
int rand10() {
while (cache_.empty()) {
generate();
}
auto result = cache_.back(); cache_.pop_back();
return result;
}
private:
void generate() {
static const int n = 19;
uint64_t curr = 0, range = static_cast<uint64_t>(pow(7, n));
for (int i = 0; i < n; ++i) {
curr += static_cast<uint64_t>(pow(7, i)) * (rand7() - 1);
}
while (curr < range / 10 * 10) {
cache_.emplace_back(curr % 10 + 1);
curr /= 10;
range /= 10;
}
}
vector<int> cache_;
};
// Time: O(2 * (1 + (9/49) + (9/49)^2 + ...)) = O(2/(1-(9/49)) = O(2.45)
// Space: O(1)
class Solution2 {
public:
int rand10() {
while (true) {
int x = (rand7() - 1) * 7 + (rand7() - 1);
if (x < 40) {
return x % 10 + 1;
}
}
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助