題目如下:
題目
這道題的主要解題思路是利用矩形所包含的整數(shù)坐標(biāo)點(diǎn)來生成對于的權(quán)重燥筷,如下圖所示:
權(quán)重計(jì)算
對于一個長寬為a蚤假,b的矩形,我們可以通過: (a+1)*(b+1)來獲取其包含整數(shù)點(diǎn)的數(shù)量從而生成對應(yīng)的權(quán)重信息。根據(jù)權(quán)重信息宋舷,有兩種解法:
解法①:使用random.choices() 根據(jù)權(quán)重選擇矩形,然后生成隨機(jī)點(diǎn)瓢姻。 參考代碼如下:
'''
@auther: Jedi.L
@Date: Tue, Feb 26, 2019 12:10
@Blog: www.tundrazone.com
@Email: xiangyangan@gmail.com
'''
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(), 根據(jù)權(quán)重產(chǎn)生的累積概率選擇矩形祝蝠,再生成隨機(jī)點(diǎn)。參考代碼如下:
'''
@auther: Jedi.L
@Date: Tue, Feb 26, 2019 12:10
@Blog: www.tundrazone.com
@Email: xiangyangan@gmail.com
'''
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版 持續(xù)更新)]
(http://www.reibang.com/p/60b5241ca28e)
ps:如果您有好的建議幻碱,歡迎交流 :-D绎狭,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)