Skip to content

Commit 7af376d

Browse files
committedMar 3, 2025
Add solution #497
1 parent 5459b7b commit 7af376d

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,7 @@
398398
494|[Target Sum](./0494-target-sum.js)|Medium|
399399
495|[Teemo Attacking](./0495-teemo-attacking.js)|Easy|
400400
496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy|
401+
497|[Random Point in Non-overlapping Rectangles](./0497-random-point-in-non-overlapping-rectangles.js)|Medium|
401402
500|[Keyboard Row](./0500-keyboard-row.js)|Easy|
402403
501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy|
403404
502|[IPO](./0502-ipo.js)|Hard|
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 497. Random Point in Non-overlapping Rectangles
3+
* https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array of non-overlapping axis-aligned rectangles rects where
7+
* rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the
8+
* ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an
9+
* algorithm to pick a random integer point inside the space covered by one of the given
10+
* rectangles. A point on the perimeter of a rectangle is included in the space covered by
11+
* the rectangle.
12+
*
13+
* Any integer point inside the space covered by one of the given rectangles should be equally
14+
* likely to be returned.
15+
*
16+
* Note that an integer point is a point that has integer coordinates.
17+
*
18+
* Implement the Solution class:
19+
* - Solution(int[][] rects) Initializes the object with the given rectangles rects.
20+
* - int[] pick() Returns a random integer point [u, v] inside the space covered by one of the
21+
* given rectangles.
22+
*/
23+
24+
/**
25+
* @param {number[][]} rects
26+
*/
27+
var Solution = function(rects) {
28+
this.rects = rects;
29+
this.areas = rects.map(([x1, y1, x2, y2]) => (x2 - x1 + 1) * (y2 - y1 + 1));
30+
this.totalPoints = this.areas.reduce((sum, area) => sum + area, 0);
31+
};
32+
33+
/**
34+
* @return {number[]}
35+
*/
36+
Solution.prototype.pick = function() {
37+
let random = Math.floor(Math.random() * this.totalPoints);
38+
let i = 0;
39+
while (random >= this.areas[i]) {
40+
random -= this.areas[i];
41+
i++;
42+
}
43+
const [x1, y1, x2, y2] = this.rects[i];
44+
const x = x1 + Math.floor(Math.random() * (x2 - x1 + 1));
45+
const y = y1 + Math.floor(Math.random() * (y2 - y1 + 1));
46+
return [x, y];
47+
};

0 commit comments

Comments
 (0)
Please sign in to comment.