497. leetcode題目講解(Python):非重疊矩形中的隨機點(Random Point in Non-overlapping Rectangles)

題目如下:


這道題的主要解題思路是利用矩形所包含的整數座標點來生成對於的權重,如下圖所示:

對於一個長寬爲a,b的矩形,我們可以通過: (a+1)*(b+1)來獲取其包含整數點的數量從而生成對應的權重信息。根據權重信息,有兩種解法:

解法①:使用random.choices() 根據權重選擇矩形,然後生成隨機點。 參考代碼如下:

'''
@auther: Jedi.L
@Date: Tue, Feb 26, 2019 12:10
@Blog: www.tundrazone.com
@Email: [email protected]
'''

import random

class Solution:
    def __init__(self, rects: List[List[int]]):
        self.rects = rects
        self.weights = []
        for [x_bl, y_bl, x_tr, y_tr] in self.rects:
            self.weights.append((x_tr - x_bl + 1) * (y_tr - y_bl + 1))


    def pick(self) -> List[int]:
        [x_bl, y_bl, x_tr, y_tr] = random.choices(
            self.rects, weights=self.weights)[0]
        res = [
            random.randrange(x_bl, x_tr + 1),
            random.randrange(y_bl, y_tr + 1)
        ]
        return res

解法②:使用bisect.bisect_left(), 根據權重產生的累積概率選擇矩形,再生成隨機點。參考代碼如下:

'''
@auther: Jedi.L
@Date: Tue, Feb 26, 2019 12:10
@Blog: www.tundrazone.com
@Email: [email protected]
'''

import random
import bisect

class Solution:
    def __init__(self, rects):
        self.rects, self.ranges, point_sum = rects, [], 0
        for x_bl, y_bl, x_tr, y_tr in rects:
            point_sum += (x_tr - x_bl + 1) * (y_tr - y_bl + 1)
            self.ranges.append(point_sum)

    def pick(self):
        x1, y1, x2, y2 = self.rects[bisect.bisect_left(
            self.ranges, random.randint(1, self.ranges[-1]))]
        return [random.randint(x1, x2), random.randint(y1, y2)]

源碼地址:
https://github.com/jediL/LeetCodeByPython

其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章