leetcode 470 用 Rand7() 實現 Rand10() (構造概率)
阿新 • • 發佈:2021-09-06
連結:https://leetcode-cn.com/problems/implement-rand10-using-rand7/
題目
已有方法rand7可生成 1 到 7 範圍內的均勻隨機整數,試寫一個方法rand10生成 1 到 10 範圍內的均勻隨機整數。
不要使用系統的Math.random()方法。
示例
示例 1:
輸入: 1
輸出: [7]
示例 2:
輸入: 2
輸出: [8,4]
示例 3:
輸入: 3
輸出: [8,1,10]
提示:
rand7已定義。
傳入引數:n表示rand10的呼叫次數。
進階:
rand7()呼叫次數的期望值是多少?
你能否儘量少呼叫 rand7() ?
思路
用 Rand7() 實現 Rand10()
主要是如何1/7概率實現1/10概率
可以用拋棄法構造1/2
1/5
的概率使用兩次rand7()
第一次rand7拋棄捨去隨機大於5的情況
的二次rand7拋棄捨去隨機大於6的情況 將結果分為奇數和偶數兩種情況
程式碼
// The rand7() API is already defined for you. // int rand7(); // @return a random integer in the range 1 to 7 class Solution { public: int rand10() { int p=rand7(); int q=rand7(); while(p>5) { p=rand7(); } while(q>2) q=rand7(); return q%2?p:(p+5); } };