|
| 1 | +/** |
| 2 | + * 1610. Maximum Number of Visible Points |
| 3 | + * https://leetcode.com/problems/maximum-number-of-visible-points/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array points, an integer angle, and your location, where location = [posx, posy] |
| 7 | + * and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane. |
| 8 | + * |
| 9 | + * Initially, you are facing directly east from your position. You cannot move from your position, |
| 10 | + * but you can rotate. In other words, posx and posy cannot be changed. Your field of view in |
| 11 | + * degrees is represented by angle, determining how wide you can see from any given view direction. |
| 12 | + * Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the |
| 13 | + * inclusive range of angles [d - angle/2, d + angle/2]. |
| 14 | + * |
| 15 | + * You can see some set of points if, for each point, the angle formed by the point, your position, |
| 16 | + * and the immediate east direction from your position is in your field of view. |
| 17 | + * |
| 18 | + * There can be multiple points at one coordinate. There may be points at your location, and you |
| 19 | + * can always see these points regardless of your rotation. Points do not obstruct your vision to |
| 20 | + * other points. |
| 21 | + * |
| 22 | + * Return the maximum number of points you can see. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number[][]} points |
| 27 | + * @param {number} angle |
| 28 | + * @param {number[]} location |
| 29 | + * @return {number} |
| 30 | + */ |
| 31 | +var visiblePoints = function(points, angle, location) { |
| 32 | + const angles = []; |
| 33 | + let originPoints = 0; |
| 34 | + const [x0, y0] = location; |
| 35 | + |
| 36 | + for (const [x, y] of points) { |
| 37 | + if (x === x0 && y === y0) { |
| 38 | + originPoints++; |
| 39 | + continue; |
| 40 | + } |
| 41 | + const radian = Math.atan2(y - y0, x - x0); |
| 42 | + const degree = (radian * 180) / Math.PI; |
| 43 | + angles.push(degree); |
| 44 | + angles.push(degree + 360); |
| 45 | + } |
| 46 | + |
| 47 | + angles.sort((a, b) => a - b); |
| 48 | + const threshold = angle; |
| 49 | + let maxVisible = 0; |
| 50 | + let left = 0; |
| 51 | + |
| 52 | + for (let right = 0; right < angles.length; right++) { |
| 53 | + while (angles[right] - angles[left] > threshold) { |
| 54 | + left++; |
| 55 | + } |
| 56 | + maxVisible = Math.max(maxVisible, right - left + 1); |
| 57 | + } |
| 58 | + |
| 59 | + return maxVisible + originPoints; |
| 60 | +}; |
0 commit comments