本文最后更新于189 天前,其中的信息可能已经过时,如有错误请发送邮件到2446865563@qq.com
1.题目基本信息
1.1.题目描述
给定方法 rand7 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。
你只能调用 rand7() 且不能调用其他方法。请不要使用系统的 Math.random() 方法。
每个测试用例将有一个内部参数 n,即你实现的函数 rand10() 在测试时将被调用的次数。请注意,这不是传递给 rand10() 的参数。
1.2.题目地址
https://leetcode.cn/problems/implement-rand10-using-rand7/description/
2.解题方法
2.1.解题思路
拒绝采样
3.解题代码
python3代码
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
# 思路:拒绝采样
while True:
row = rand7()
col = rand7()
# > 计算(row,col)坐标在矩阵中的编号
x = (row - 1) * 7 + col - 1
if x < 40:
return x // 4 + 1
4.执行结果










