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


    题目描述

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

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

     

    示例 1:

    输入: 1
    输出: [7]
    

    示例 2:

    输入: 2
    输出: [8,4]
    

    示例 3:

    输入: 3
    输出: [8,1,10]
    

     

    提示:

    1. rand7 已定义。
    2. 传入参数: n 表示 rand10 的调用次数。

     

    进阶:

    1. rand7()调用次数的 期望值 是多少 ?
    2. 你能否尽量少调用 rand7() ?

    解题思路

    用randN生成randM,其中N<M的基本思想是:

    • 首先找到一个能覆盖M整数倍的随机序列,对于此题来说,最少能全覆盖的范围是1~49,即(rand7() - 1) * 7 + rand7(),调用此式子并舍去大于40的数,可以得到1~40的均匀分布
    • 得到了1~40的均匀分布后,接着模10取余即可得到0~9的均匀分布,然后加1即是rand10

    代码

     1 // The rand7() API is already defined for you.
     2 // int rand7();
     3 // @return a random integer in the range 1 to 7
     4 
     5 class Solution {
     6 public:
     7     int rand10() {
     8         int r = (rand7() - 1) * 7 + rand7();
     9         while(r > 40)
    10             r = (rand7() - 1) * 7 + rand7();
    11         return r % 10 + 1;
    12     }
    13 };
  • 相关阅读:
    图片处理
    define 常量的定义和读取
    curl
    stream_get_contents 和file_get_content的区别
    php flock 文件锁
    字符串函数
    php 常量
    debug_backtrace()
    pathlib模块替代os.path
    Python中对 文件 的各种骚操作
  • 原文地址:https://www.cnblogs.com/wmx24/p/9582951.html
Copyright © 2020-2023  润新知