LC 470. Implement Rand10() Using Rand7()
Posted ethanhong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 470. 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]
Runtime: 88 ms, faster than 42.31% of C++ online submissions for Implement Rand10() Using Rand7().
不会做,好题,是一道极限近似题。
https://leetcode.com/problems/implement-rand10-using-rand7/discuss/150301/Three-line-Java-solution-the-idea-can-be-generalized-to-%22Implement-RandM()-Using-RandN()%22
class Solution {
public:
int rand10() {
int ret = 40;
while(ret >= 40) {
ret = 7 *(rand7()-1) + rand7()-1;
}
return ret%10+1;
}
};
以上是关于LC 470. Implement Rand10() Using Rand7()的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode470 - Implement Rand10() Using Rand7() - Medium (Python)
[LeetCode] 470. Implement Rand10() Using Rand7()
470. Implement Rand10() Using Rand7() (拒绝采样Reject Sampling)
[M数学] lc470. 用 Rand7() 实现 Rand10()(概率+拒绝采样+经典好题)