497 Random Point in Non-overlapping Rectangles
1. Question
Given a list ofnon-overlapping axis-aligned rectanglesrects, write a functionpickwhich randomly and uniformily picks aninteger pointin the space covered by the rectangles.
Note:
An integer point is a point that has integer coordinates.
A point on the perimeter of a rectangle is included in the space covered by the rectangles.
ith rectangle =rects[i]=[x1,y1,x2,y2], where[x1, y1]are the integer coordinates of the bottom-left corner, and[x2, y2]are the integer coordinates of the top-right corner.length and width of each rectangle does not exceed
2000.1 <= rects.length <= 100pickreturn a point as an array of integer coordinates[p_x, p_y]pickis called at most10000times.
Example 1:
Input:
["Solution","pick","pick","pick"]
[[[[1,1,5,5]]],[],[],[]]
Output:
[null,[4,1],[4,1],[3,3]]Example 2:
Explanation of Input Syntax:
The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the array of rectanglesrects.pick has no arguments. Arguments are always wrapped with a list, even if there aren't any.
2. Implementation
(1) TreeMap
思路: 将累积面积的和放入TreeMap中,key是累积面积和,value是对应矩阵的index。调用pick()时,我们生成在[1, totalArea]的随机数,然后再通过treemap找到这个随机数所落入的累积面积和的区间,即找到最小的key,使得key对应的value大于等于随机数
(2) Cumulative Sum Array
3. Time & Space Complexity
(1) TreeMap: solution(): O(nlogn), pick(): O(logn)
(2) One Pass: solution(): O(n), pick(): O(n)
Last updated
Was this helpful?