[LeetCode] Random Point in Non-overlapping Rectangles

497. Random Point in Non-overlapping Rectangles

You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.

Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.

Note that an integer point is a point that has integer coordinates.

Implement the Solution class:

  • Solution(int[][] rects) Initializes the object with the given rectangles rects.
  • int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
vector<int> sum;
vector<vector<int>> r;

int size(vector<int>& r) {
return (r[3]-r[1]+1)*(r[2]-r[0]+1);
}
public:
Solution(vector<vector<int>>& rects): r(rects) {
for(auto& r: rects) {
sum.push_back(size(r) + sum.empty()?0:sum.back());
}
}

vector<int> pick() {
int rnd = rand()%sum.back();
int pos = upper_bound(sum.begin(),sum.end(),rnd) - sum.begin();

return {rand()%(r[pos][2]-r[pos][0]+1)+r[pos][0], rand()%(r[pos][3]-r[pos][1]+1)+r[pos][1]};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/28/PS/LeetCode/random-point-in-non-overlapping-rectangles/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.