• (Java) LeetCode 470. Implement Rand10() Using Rand7() —— 用 Rand7() 实现 Rand10()


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

    一看就不会系列…不过还是在网上找到了思路。关键是如何利用rand7()等概率的生成1~10的数字。rand7()能做什么?等概率的生成1~7。但其实进阶一步也可以等概率的生成1~x,其中x是任意不大于7的数。具体做法就是先用rand7()生成一个1~7的数,之后舍弃大于x的数。于是乎,舍弃7的话就可以等概率生成1~6,就等于等概率生成0或1,只要对2取余就好。之后同样的方法舍弃6,7就可以等概率的生成1~5。两个结合在一起,如果第一步生成的是0,那么直接返回第二步的数(1~5);如果第一步生成的是1,那么返回第二步的数+5(6~10)。因为生成第一步生成0或1等概率,第二步生成1~5亦等概率,所以最后组合起来1~10依然等概率。

    而至于这么做为什么不是最优解,还看这个文章及其下面的评论。https://leetcode.com/articles/implement-rand10-using-rand7/


    Java

    /**
     * The rand7() API is already defined in the parent class SolBase.
     * public int rand7();
     * @return a random integer in the range 1 to 7
     */
    class Solution extends SolBase {    
        private int oddOrEven() {
            int num = 0;
            while ((num = rand7()) > 6);
            return num % 2;
        }
        
        private int smallerOrBiggerThan5() {
            int num = 0;
            while ((num = rand7()) > 5);
            return num;
        }
        
        public int rand10() {
            int num1 = oddOrEven();
            int num2 = smallerOrBiggerThan5();
            if (num1 == 1) return num2 + 5;
            else return num2;
        }
    }
  • 相关阅读:
    STL中队列queue的常见用法
    牛客网剑指offer第17题——树的子结构
    《剑指offer》网络大神所有习题题解
    牛客网剑指offer第4题——重建二叉树
    牛客网剑指offer第56题——删除链表中重复的节点
    图像处理中的求导问题
    hash_set和hash_map
    hashtable初步——一文初探哈希表
    数据结构-链表的那些事(下)(二)
    数据结构-链表的那些事(上)(一)
  • 原文地址:https://www.cnblogs.com/tengdai/p/9438422.html
Copyright © 2020-2023  润新知