|
| 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