zoukankan      html  css  js  c++  java
  • 497. Random Point in Non-overlapping Rectangles

    1. 问题

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

    2. 思路

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

    init:时间复杂度O(n),空间复杂度O(n)
    pick:时间复杂度O(n),空间复杂度O(1)

    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()
    

    4. 类似题目

    528. Random Pick with Weight

  • 相关阅读:
    Matplotlib 绘图库 基本使用方法
    linux socat命令
    linux shell重定向
    linux man命令
    bashttpd使用手册
    libcurl代码示例
    vim文件头部注释配置
    linux join命令
    iterm2切换显示屏vim乱行解决
    分形与混沌
  • 原文地址:https://www.cnblogs.com/liaohuiqiang/p/9860862.html
Copyright © 2011-2022 走看看