497. 非重叠矩形中的随机点

exiaohu 于 2022-06-09 发布

题目链接:497. 非重叠矩形中的随机点

记录每个矩形的面积,以面积为权重采样。

from bisect import bisect_left
from random import random, randint
from typing import List


class Solution:

    def __init__(self, rects: List[List[int]]):
        ans, areas = 0, []
        for a, b, x, y in rects:
            ans += (x - a + 1) * (y - b + 1)
            areas.append(ans)

        self.ans, self.areas, self.rects = ans, areas, rects

    def pick(self) -> List[int]:
        a, b, x, y = self.rects[bisect_left(self.areas, random() * self.ans)]
        return [randint(a, x), randint(b, y)]