[LeetCode] 470. Implement Rand10() Using Rand7()

2021/9/6 6:06:53

本文主要是介绍[LeetCode] 470. Implement Rand10() Using Rand7(),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.

Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().

Follow up:

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

Example 1:

Input: n = 1
Output: [2]

Example 2:

Input: n = 2
Output: [2,8]

Example 3:

Input: n = 3
Output: [3,8,10]

Constraints:

  • 1 <= n <= 105

用 Rand7() 实现 Rand10()。

已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。

不要使用系统的 Math.random() 方法。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-rand10-using-rand7
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数学/概率的题目。题目给了一个 Rand7() 函数,可以随机生成一个1 - 7的数字,现在请你用这个函数生成 1 到 10 范围内的均匀随机整数。我这里直接引用了一个写的很好的帖子。

因为 Rand7() 只能生成 1 - 7 这几个数字,无法生成 8 - 10 这几个数字,所以我们只能通过如下这几个步骤来解决这个问题。

  1. rand7() 等概率地产生 1,2,3,4,5,6,7.
  2. rand7() - 1 等概率地产生 [0,6].
  3. (rand7() - 1) *7 等概率地产生0, 7, 14, 21, 28, 35, 42
  4. (rand7() - 1) * 7 + (rand7() - 1) 等概率地产生 [0, 48] 这 49 个数字
  5. 如果步骤 4 的结果大于等于 40,那么就重复步骤 4,直到产生的数小于 40
  6. 把步骤 5 的结果 mod 10 再加 1, 就会等概率的随机生成 [1, 10]

————————————————
版权声明:本文为CSDN博主「负雪明烛」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/fuxuemingzhu/article/details/81809478

简化下来就是rand7 -> rand49 -> rand40 -> rand10

时间O(1)

空间O(1)

Java实现

 1 /**
 2  * The rand7() API is already defined in the parent class SolBase.
 3  * public int rand7();
 4  * @return a random integer in the range 1 to 7
 5  */
 6 class Solution extends SolBase {
 7     public int rand10() {
 8         int res = 40;
 9         // rand7() - 1 等概率生成了0-6
10         // 再乘以7 就等概率生成了0 - 42
11         // 再加 rand7() - 1 等概率生成了0 - 48
12         while (res >= 40) {
13             res = 7 * (rand7() - 1) + (rand7() - 1);
14         }
15         return res % 10 + 1;
16     }
17 }

 

LeetCode 题目总结



这篇关于[LeetCode] 470. Implement Rand10() Using Rand7()的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程