面試題_數學相關

470. 用 Rand7() 實現 Rand10()

給定方法 rand7 可生成 [1,7] 範圍內的均勻隨機整數,試寫一個方法 rand10 生成 [1,10] 範圍內的均勻隨機整數。

你只能調用 rand7() 且不能調用其他方法。請不要使用系統的 Math.random() 方法。

每個測試用例將有一個內部參數 n,即你實現的函數 rand10() 在測試時將被調用的次數。請注意,這不是傳遞給 rand10() 的參數。

示例 1:

輸入: 1
輸出: [2]
示例 2:

輸入: 2
輸出: [2,8]
示例 3:

輸入: 3
輸出: [3,8,10]

提示:

1 <= n <= 105

進階:
rand7()調用次數的 期望值 是多少 ?
你能否儘量少調用 rand7() ?

非常好的題解:解析

# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7

class Solution:
    # 解析:https://leetcode.cn/problems/implement-rand10-using-rand7/solution/xiang-xi-si-lu-ji-you-hua-si-lu-fen-xi-zhu-xing-ji/
    def rand10(self):
        """
        :rtype: int
        """
        row, col, idx = 0, 0, 0
        while True:
            row = rand7()
            col = rand7()
            idx = (row - 1) * 7 + col
            if idx <= 40:
                return 1 + (idx - 1) % 10
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7

class Solution:
    # 解析:https://leetcode.cn/problems/implement-rand10-using-rand7/solution/xiang-xi-si-lu-ji-you-hua-si-lu-fen-xi-zhu-xing-ji/
    def rand10(self):
        """
        :rtype: int
        """
        # row, col, idx = 0, 0, 0
        # while True:
        #     row = rand7()
        #     col = rand7()
        #     idx = (row - 1) * 7 + col
        #     if idx <= 40:
        # 返回結果,+1是爲了解決 40%10爲0的情況
        #         return 1 + (idx - 1) % 10

        while True:
            num = (rand7() - 1)*7 + rand7()
            # 如果在40以內,那就直接返回
            if num <= 40:
                return 1 + (num - 1) % 10
            # 說明剛剛生成的在41-49之間,利用隨機數再操作一遍
            num = (num - 40 - 1) * 7 + rand7()
            if num <= 60:
                return 1 + (num) % 10
            # 說明剛剛生成在61-63之間,利用隨機數再操作一遍
            num = (num - 60 - 1) * 7 + rand7()
            if num <= 20:
                return 1 + (num) % 10
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章