forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
497_Random_Point_in_Non-overlapping_Rectangles
81 lines (69 loc) · 2.3 KB
/
497_Random_Point_in_Non-overlapping_Rectangles
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Leetcode 497: Random Point in Non-overlapping Rectangles
Detailed video explanation: https://youtu.be/8kwPXbTMSnk
=========================================================
C++:
----
class Solution {
int num_pts;
vector<int> rect_cum_count;
vector<vector<int>> rects;
public:
Solution(vector<vector<int>>& rects) {
num_pts = 0;
this->rects = rects;
for(vector<int>& rect: rects){
num_pts += (rect[2] - rect[0] + 1)*(rect[3] - rect[1] + 1);
rect_cum_count.push_back(num_pts);
}
}
vector<int> pick() {
int pt_idx = rand() % num_pts;
int l = 0, r = rects.size()-1;
while(l < r){
int mid = l + (r-l)/2;
if(rect_cum_count[mid] <= pt_idx) l = mid+1;
else r = mid;
}
// l = rectangle index
vector<int>& rect = rects[l];
int x_pts = rect[2] - rect[0] + 1;
int y_pts = rect[3] - rect[1] + 1;
int pts_in_rect = x_pts*y_pts;
int pt_start = rect_cum_count[l] - pts_in_rect;
int offset = pt_idx - pt_start;
return {rect[0] + offset%x_pts, rect[1] + offset/x_pts};
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(rects);
* vector<int> param_1 = obj->pick();
*/
Python3:
-------
class Solution:
def __init__(self, rects: List[List[int]]):
self.num_pts = 0
self.rects = rects
self.rect_cum_count = []
for rect in rects:
self.num_pts += (rect[2] - rect[0] + 1)*(rect[3] - rect[1] + 1)
self.rect_cum_count.append(self.num_pts)
def pick(self) -> List[int]:
pt_idx = random.randint(0, self.num_pts-1)
l, r = 0, len(self.rects)-1
while l < r:
mid = l + (r-l)//2
if self.rect_cum_count[mid] <= pt_idx: l = mid+1
else: r = mid
# l = rectangle index
rect = self.rects[l]
x_pts = rect[2] - rect[0] + 1
y_pts = rect[3] - rect[1] + 1
pts_in_rect = x_pts*y_pts
pt_start = self.rect_cum_count[l] - pts_in_rect
offset = pt_idx - pt_start;
return [rect[0] + offset%x_pts, rect[1] + offset//x_pts]
# Your Solution object will be instantiated and called as such:
# obj = Solution(rects)
# param_1 = obj.pick()