当前位置:网站首页>【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;
}
}
};
时空复杂度一样。
边栏推荐
- color transparency parameter
- Chrome书签插件,让你实现高效整理
- IDEA common plugins
- cdh6打开oozieWeb页面,Oozie web console is disabled.
- 几道关于golang并发的面试题
- Flink学习第五天——Flink可视化控制台依赖配置和界面介绍
- recursion: method calls itself
- 程序员还差对象?new一个就行了
- 机器学习文本分类
- Dynamic Scene Deblurring with Parameter Selective Sharing and Nested Skip Connections
猜你喜欢
仿牛客网项目第三章:开发社区核心功能(详细步骤和思路)
Spark Sql之join on and和where
sys_kill系统调用
字节跳动面试官:请你实现一个大文件上传和断点续传
oozie startup error on cdh's hue, Cannot allocate containers as requested resource is greater than maximum allowed
@WebServlet注解(Servlet注解)
With a monthly salary of 12K, the butterfly changed to a new one and moved forward bravely - she doubled her monthly salary through the career change test~
在CentOS下安装MySQL
Architecture basic concept and nature of architecture
Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training
随机推荐
在linux下MySQL的常用操作命令
获取小猪民宿(短租)数据
伸展树的特性及实现
solidity
A brief analysis of mobile APP security testing in software testing, shared by a third-party software testing agency in Beijing
Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)
软件测试之移动APP安全测试简析,北京第三方软件检测机构分享
Chrome书签插件,让你实现高效整理
多御安全浏览器android版更新至1.7,改进加密协议
Programmer is still short of objects? A new one is enough
Getting started with IDEA is enough to read this article
Secondary Vocational Network Security Competition B7 Competition Deployment Process
在CentOS下安装MySQL
Calculate the angle of a line defined by two points
Always use "noopener" or "noreferrer" for links that open in a new tab
[Camp Experience Post] 2022 Cybersecurity Summer Camp
怎样做才能让这条SQL变成一条危险的SQL?
Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training
分享一份接口测试项目(非常值得练手)
numpy.hstack