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 }