LeetCode 470. Implement Rand10() Using Rand7()

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 470. Implement Rand10() Using Rand7()相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/implement-rand10-using-rand7/

题目:

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()?

题解:

Having one rand7() - 1, a, generated (0 - 6) and second rand7() - 1, b, generated, 7 * a + b could be [0 - 48].

And drawing a 2D array, find out it is evenly distributed on each number of [0 - 48]. If it is >= 40, regenerate.

Otherwise, use it % 10 + 1 would be result, random between [1, 10].

Time Complexity: O(1). 

Space: O(1).

AC 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 ind = Integer.MAX_VALUE;
 9         while(ind >= 40){
10             ind = 7 * (rand7() - 1) + (rand7() - 1);
11         }
12         
13         return ind % 10 + 1;
14     }
15 }

 

以上是关于LeetCode 470. Implement Rand10() Using Rand7()的主要内容,如果未能解决你的问题,请参考以下文章

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

leetcode470——用 Rand7() 实现 Rand10()

LC 470. Implement Rand10() Using Rand7()

470. Implement Rand10() Using Rand7() (拒绝采样Reject Sampling)

[leetcode] 69. Sqrt(x) 解题报告

69. Sqrt(x)(LeetCode)