497. Random Point in Non-overlapping Rectangles - LeetCode Solution


Binary Search

Python Code:

class Solution:
    def numPoints(self, rect) -> int:
        x1, y1, x2, y2 = rect
        return (x2 - x1 + 1) * (y2 - y1 + 1)


    def __init__(self, rects: List[List[int]]):
        self.rects = rects
        self.presum = [0]
        for i in range(len(rects)):
            self.presum.append(self.presum[-1] + self.numPoints(rects[i]))
        

    def pick(self) -> List[int]:
        n =  random.randint(1, self.presum[-1])
        i = bisect.bisect_left(self.presum, n) 
        n -= self.presum[i-1]
        x1, y1, x2, y2 = self.rects[i-1]
        q, r = divmod(n, x2 - x1 + 1)
        if r:
            return [x1 + r -1, y1 + q]
        return [x2, y1 + q -1]


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


Comments

Submit
0 Comments
More Questions

Non empty subsets
1630A - And Matching
1630B - Range and Partition
1630C - Paint the Middle
1630D - Flipping Range
1328A - Divisibility Problem
339A - Helpful Maths
4A - Watermelon
476A - Dreamoon and Stairs
1409A - Yet Another Two Integers Problem
977A - Wrong Subtraction
263A - Beautiful Matrix
180C - Letter
151A - Soft Drinking
1352A - Sum of Round Numbers
281A - Word Capitalization
1646A - Square Counting
266A - Stones on the Table
61A - Ultra-Fast Mathematician
148A - Insomnia cure
1650A - Deletions of Two Adjacent Letters
1512A - Spy Detected
282A - Bit++
69A - Young Physicist
1651A - Playoff
734A - Anton and Danik
1300B - Assigning to Classes
1647A - Madoka and Math Dad
710A - King Moves
1131A - Sea Battle