zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    vue+element实现图片上传
    react----Hooks的基本使用
    js知识点大杂烩
    vue面试题(一)
    从一个字符串中找出重复次数最多的字符?
    百度搜索
    js--拖拽
    js循环嵌套,打印图形
    js--sort()排序
    闰秒调整扫盲
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12536397.html
Copyright © 2011-2022 走看看