Leetcode 概率类型问题
470. 用 Rand7() 实现 Rand10
题目要求:
已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
Requirement: 不要使用系统的 Math.random() 方法。
概率法
该题目主要难度是平均触发生成1-10数字的概率而只能使用从1到7的平均生成方法和计算。核心目的是让1-10的结果可以以相同的概率通过1-7的内容数据凑出来。
方式:
通过计算7 * 7 = 49的方法来平均产生1-49的数据,然后抛弃大于40的数据
剩下符合条件的数据进行与 10 的取余计算,平均出现余数的概率是相同的,
以实现产生相同概率的 1-10 数据。
代码:
/**
* 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 {
public int rand10() {
int result = 50; // 自定义初始值用于 while 循环
while (result > 40) {
// 使用 rand7() 方法2次来获得随机的 1-49 数据
result = (rand7() - 1) * 7 + rand7();
}
return result % 10 + 1;
}
}