面试题_数学相关

470. 用 Rand7() 实现 Rand10()

给定方法 rand7 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。

你只能调用 rand7() 且不能调用其他方法。请不要使用系统的 Math.random() 方法。

每个测试用例将有一个内部参数 n,即你实现的函数 rand10() 在测试时将被调用的次数。请注意,这不是传递给 rand10() 的参数。

示例 1:

输入: 1
输出: [2]
示例 2:

输入: 2
输出: [2,8]
示例 3:

输入: 3
输出: [3,8,10]

提示:

1 <= n <= 105

进阶:
rand7()调用次数的 期望值 是多少 ?
你能否尽量少调用 rand7() ?

非常好的题解:解析

# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7

class Solution:
    # 解析:https://leetcode.cn/problems/implement-rand10-using-rand7/solution/xiang-xi-si-lu-ji-you-hua-si-lu-fen-xi-zhu-xing-ji/
    def rand10(self):
        """
        :rtype: int
        """
        row, col, idx = 0, 0, 0
        while True:
            row = rand7()
            col = rand7()
            idx = (row - 1) * 7 + col
            if idx <= 40:
                return 1 + (idx - 1) % 10
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7

class Solution:
    # 解析:https://leetcode.cn/problems/implement-rand10-using-rand7/solution/xiang-xi-si-lu-ji-you-hua-si-lu-fen-xi-zhu-xing-ji/
    def rand10(self):
        """
        :rtype: int
        """
        # row, col, idx = 0, 0, 0
        # while True:
        #     row = rand7()
        #     col = rand7()
        #     idx = (row - 1) * 7 + col
        #     if idx <= 40:
        # 返回结果,+1是为了解决 40%10为0的情况
        #         return 1 + (idx - 1) % 10

        while True:
            num = (rand7() - 1)*7 + rand7()
            # 如果在40以内,那就直接返回
            if num <= 40:
                return 1 + (num - 1) % 10
            # 说明刚刚生成的在41-49之间,利用随机数再操作一遍
            num = (num - 40 - 1) * 7 + rand7()
            if num <= 60:
                return 1 + (num) % 10
            # 说明刚刚生成在61-63之间,利用随机数再操作一遍
            num = (num - 60 - 1) * 7 + rand7()
            if num <= 20:
                return 1 + (num) % 10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值