497. Random Point in Non-overlapping Rectangles

Posted PilgrimHui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了497. Random Point in Non-overlapping Rectangles相关的知识,希望对你有一定的参考价值。

1. 问题

给定一系列不重叠的矩形,在这些矩形中随机采样一个整数点。

2. 思路

(1)一个矩形的可采样点个数就相当于它的面积,可以先依次对每个矩形的面积累加存起来(相当于概率分布中的分布累积函数CDF,Cumulative Distribution Function)。
(2)从 [1, 总面积] 中随机取一个数n(面积),表示要取第几个点,找到这个点即可完成题目要求的随机采样。
(3)找点可以先使用python的bisect_left方法,根据这个数(面积)在多个累加面积之间寻找合适的位置(第几个矩形)。然后根据这个数(面积)在那个矩形里找到这个点。
(4)bisect_left的作用是对已排序数组,查找目标数值将会插入的位置并返回(但是不会插入),数值相同时返回靠左的位置。

3. 代码

import random
import bisect

class Solution(object):
    def __init__(self, rects):
        """
        :type rects: List[List[int]]
        """
        self.rects = rects
        sums = 0
        self.accumulate = []
        for x1, y1, x2, y2 in rects:
            sums += (y2 - y1 + 1) * (x2 - x1 + 1)
            self.accumulate.append(sums)

    def pick(self):
        """
        :rtype: List[int]
        """
        n = random.randint(1, self.accumulate[-1])
        i = bisect.bisect_left(self.accumulate, n)
        x1, y1, x2, y2 = self.rects[i]
        if(i > 0):
            n -= self.accumulate[i - 1]
        n -= 1
        return [x1 + n % (x2 - x1 + 1), y1 + n / (x2 - x1 + 1)]

# Your Solution object will be instantiated and called as such:
# obj = Solution(rects)
# param_1 = obj.pick()



以上是关于497. Random Point in Non-overlapping Rectangles的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Generate Random Point in a Circle ????????????????????????

478. Generate Random Point in a Circle

SLS与CDCL结合——文献学习CCAnr: A Configuration Checking Based Local Search Solver for Non-random Satisfiabil

A non-collectible assembly may not reference a collectible assembly异常

A linked list is given such that each node contains an additional random pointer which could point t

OSPF协议所支持的网络类型中都有哪些是需要选举DR和BDR的?