@@ -64,9 +64,9 @@ solution.pick(); // 返回 [0, 0]</pre>
64
64
65
65
<!-- 这里可写通用的实现逻辑 -->
66
66
67
- 前缀和 + 二分查找。
67
+ ** 方法一: 前缀和 + 二分查找**
68
68
69
- 将矩形面积求前缀和 s ,然后随机获取到一个面积 v ,利用二分查找定位到是哪个矩形,然后继续随机获取该矩形的其中一个整数点坐标即可。
69
+ 将矩形面积求前缀和 $s$ ,然后随机获取到一个面积 $v$ ,利用二分查找定位到是哪个矩形,然后继续随机获取该矩形的其中一个整数点坐标即可。
70
70
71
71
<!-- tabs:start -->
72
72
@@ -85,14 +85,8 @@ class Solution:
85
85
86
86
def pick (self ) -> List[int ]:
87
87
v = random.randint(1 , self .s[- 1 ])
88
- left, right = 0 , len (self .s) - 1
89
- while left < right:
90
- mid = (left + right) >> 1
91
- if self .s[mid] >= v:
92
- right = mid
93
- else :
94
- left = mid + 1
95
- x1, y1, x2, y2 = self .rects[left]
88
+ idx = bisect_left(self .s, v)
89
+ x1, y1, x2, y2 = self .rects[idx]
96
90
return [random.randint(x1, x2), random.randint(y1, y2)]
97
91
98
92
@@ -159,18 +153,12 @@ public:
159
153
this->rects = rects;
160
154
srand(time(nullptr));
161
155
}
162
-
156
+
163
157
vector<int > pick () {
164
158
int n = rects.size();
165
159
int v = 1 + rand() % s[n];
166
- int left = 0, right = n;
167
- while (left < right)
168
- {
169
- int mid = (left + right) >> 1;
170
- if (s[mid] >= v) right = mid;
171
- else left = mid + 1;
172
- }
173
- auto& rect = rects[left - 1];
160
+ int idx = lower_bound(s.begin(), s.end(), v) - s.begin();
161
+ auto& rect = rects[idx - 1];
174
162
int x = rect[0] + rand() % (rect[2] - rect[0] + 1);
175
163
int y = rect[1] + rand() % (rect[3] - rect[1] + 1);
176
164
return {x, y};
0 commit comments