1610. Maximum Number of Visible Points

can refer this:

https://leetcode.com/problems/maximum-number-of-visible-points/discuss/1595464/Java-oror-Sliding-Window-oror-Change-to-Degree-oror-Explained-Thoroughly

T: O(nlogn), n is length of points
S: O(n)
class Solution {
    public int visiblePoints(List<List<Integer>> points, int angle, List<Integer> location) {
        List<Double> angles = new ArrayList<>();
        int same = 0;
        for (List<Integer> point : points) {
            // 被觀察的點 x, y - 看的地方的座標
            int dx = point.get(0) - location.get(0);
            int dy = point.get(1) - location.get(1);
            
            // 有些點可能是重合的, 代表 不管什麼角度 都看得到這些點
            // 所以單獨計算, 最後加到結果
            if (dx == 0 && dy == 0) {
                same++;
            } else {
                // 得到各點, 各距離的角度
                double degree = Math.atan2(dy, dx)*(180/Math.PI);
                angles.add(degree);
            }
        }
        // 排序一下
        Collections.sort(angles);
        
        // for circular 處理, 因為在尾端 sliding window 可能處理不到, 所以需要
        // n 記得要提出來, 不然會跟著變大...因為再加資料
        int n = angles.size();
        for (int i = 0; i < n; i++) { 
            angles.add(angles.get(i)+360); // append 一樣的 degree 但都多家 360
        }
        
        // sliding window
        int res = 0;
        int right = 0;
        for (int left = 0; left < angles.size(); left++) {
            while (right < angles.size() && angles.get(right) - angles.get(left) <= angle) {
                right++;
            }
            res = Math.max(res, right - left);
        }
        return res + same;
    }
}

/*
ex:
left
           right
[10,20, 29]
angle = 30

cal each point dx. dy (points to location's dist)

use dx. dy get angles list (degree = Math.atan2(dy, dx)*(180/Math.PI))

sort angles list 

handle circular issue: for i = 0~n, append each angles with +360 degree

then do the sliding window, window size = angle

T: O(nlogn), n is length of points
S: O(n)

*/

這樣也可以

more explain

Last updated

Was this helpful?