当前位置:网站首页>【Leetcode】470. Implement Rand10() Using Rand7()
【Leetcode】470. Implement Rand10() Using Rand7()
2022-08-01 23:47:00 【记录算法题解】
题目地址:
https://leetcode.com/problems/implement-rand10-using-rand7/description/
假设我们有一个API叫rand7()
可以等概率随机产生 1 ∼ 7 1\sim 7 1∼7中的一个数,要求利用这个API实现rand10()
。
参考https://blog.csdn.net/qq_46105170/article/details/109269492。考虑API被叫的次数,每轮有 40 49 \frac{40}{49} 4940的概率停止,从而轮数的期望就是 49 40 \frac{49}{40} 4049,而每轮叫两次,所以叫的次数的期望是 49 20 \frac{49}{20} 2049。代码如下:
import java.util.Random;
class Solution extends SolBase {
public int rand10() {
while (true) {
int x = rand7(), y = rand7();
int n = 7 * (x - 1) + y;
if (n <= 40) {
return (n - 1) / 4 + 1;
}
}
}
}
abstract class SolBase {
int rand7() {
return new Random().nextInt(7) + 1;
}
}
平均时间复杂度 O ( 1 ) O(1) O(1),空间 O ( 1 ) O(1) O(1)。
C++:
class Solution {
public:
int rand10() {
while (true) {
int t = (rand7() - 1) * 7 + rand7();
if (t <= 40) return (t - 1) / 4 + 1;
}
}
};
时空复杂度一样。
边栏推荐
- async和await用法介绍
- What can be done to make this SQL into a dangerous SQL?
- 仿牛客网项目第三章:开发社区核心功能(详细步骤和思路)
- Making a Simple 3D Renderer
- ELK log collection
- recursion: method calls itself
- DRF generating serialization class code
- Loading configuration of Nacos configuration center
- CDH6的Hue打开出现‘ascii‘ codec can‘t encode characters
- CDH6 Hue to open a "ASCII" codec can 't encode characters
猜你喜欢
Spark Sql之join on and和where
The monthly salary of the test post is 5-9k, how to increase the salary to 25k?
[Camp Experience Post] 2022 Cybersecurity Summer Camp
Share an interface test project (very worth practicing)
Various Joins of Sql
[LeetCode304周赛] 两道关于基环树的题 6134. 找到离给定两个节点最近的节点,6135. 图中的最长环
多御安全浏览器android版更新至1.7,改进加密协议
[email protected]与
YOLO等目标检测模型的非极大值抑制NMS和评价指标(Acc, Precision, Recall, AP, mAP, RoI)、YOLOv5中[email protected]与
2022第六届强网杯部分wp
字节跳动面试官:请你实现一个大文件上传和断点续传
随机推荐
2022还想上岸学习软件测试必看,测试老鸟的肺腑之言...
工件SSMwar exploded 部署工件时出错。请参阅服务器日志了解详细信息
cdh的hue上oozie启动报错,Cannot allocate containers as requested resource is greater than maximum allowed
如何用Redis实现分布式锁?
Share an interface test project (very worth practicing)
Classical Literature Reading--DLO
Dynamic Scene Deblurring with Parameter Selective Sharing and Nested Skip Connections
ELK log collection
Docker实践经验:Docker 上部署 mysql8 主从复制
PostgreSQL Basics--Common Commands
@Resource和@Autowired的区别
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
cdh6 opens oozieWeb page, Oozie web console is disabled.
Access the selected node in the console
UI自动化测试框架搭建-标记性能较差用例
JAX-based activation function, softmax function and cross entropy function
邻接表与邻接矩阵
20220725资料更新
技术分享 | 接口测试中如何使用Json 来进行数据交互 ?
Special characters & escapes in bat