【LeetCode】470. Implement Rand10() Using Rand7() 解题报告(Python)

【LeetCode】470. Implement Rand10() Using Rand7() 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/

题目地址:https://leetcode.com/problems/implement-rand10-using-rand7/description/

题目描述:

Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.

Do NOT use system’s Math.random().

Example 1:

Input: 1
Output: [7]

Example 2:

Input: 2
Output: [8,4]

Example 3:

Input: 3
Output: [8,1,10]

Note:

  1. rand7 is predefined.
  2. Each testcase has one argument: n, the number of times that rand10 is called.

Follow up:

  1. What is the expected value for the number of calls to rand7() function?
  2. Could you minimize the number of calls to rand7()?

题目大意

利用一个范围在1~7的随机数产生器,构造一个范围在1~10的随机数产生器。

解题方法

范围在1~7的随机数产生器,即1~7各个数字出现的概率皆为1/7.
范围在1~10的随机数产生器,即1~10各个数字出现的概率皆为1/10.

这个题的构造思路是先构造一个randN,这个N必须是10的整数倍,然后randN % 10就可以得到了rand10.

所以可以从rand7先构造出rand49,再把rand49中大于等于40的都过滤掉,这样就得到了rand40,在对10取余即可。

所以:

rand7 –> rand49 –> rand40 –> rand10.

构造rand49的方式是:

7 * (rand7() - 1) + rand7() - 1

这个方法我觉得最好要记住。

# 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 """
        return self.rand40() % 10 + 1

    def rand49(self):
        """ random integer in 0 ~ 48 """
        return 7 * (rand7() - 1) + rand7() - 1

    def rand40(self):
        """ random integer in 0 ~ 40 """
        num = self.rand49()
        while num >= 40:
            num = self.rand49()
        return num

日期

2018 年 8 月 18 日 ———— 天在下雨

点赞