[Google] LeetCode 1610 Maximum Number of Visible Points 极角排序


You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.

Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].

You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.

There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.

Return the maximum number of points you can see.

Solution

给定一个坐标,以及其他点,问给定视角,最多能看到多少个点。

以 /(location/) 为原点,计算出其他点与其的夹角。这里使用 /(cpp/) 的 /(atan2/) 得到反正切。

得到夹角以后,进行排序。注意到这是一个圈,所以我们同时得 /(push/_back/) /(angle[i]+360/)

最后利用滑动窗口即可

点击查看代码
class Solution {
private:
    long double pi = acos(-1.0);
    
    long double GetAngle(long double y, long double x){
        return (atan2(y,x)*180.0)/pi;
    }
    
    vector<long double> angles;
    int ans=0;
    
public:
    int visiblePoints(vector<vector<int>>& points, int angle, vector<int>& location) {
        int sx = location[0], sy = location[1];
        int n = points.size();
        for(int i=0;i<n;i++){
            if(points[i][0]==sx && points[i][1]==sy)ans++;
            else{
                long double dx = 1.0*(points[i][0]-sx);
                long double dy = 1.0*(points[i][1]-sy);
                
                long double ang = GetAngle(dy, dx);
                angles.push_back(ang);
            }
        }
        sort(angles.begin(), angles.end());
        n = angles.size();
        for(int i=0;i<n;i++){
            // circle
            angles.push_back(angles[i]+360.0);
        }
        int l = 0, cnt = 0;
        for(int i=0;i<angles.size();i++){
            while(angles[i]-angles[l]>angle)l++;
            cnt=max(cnt, i-l+1);
        }
        ans+=cnt;
        return ans;
    }
};

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281765.html

(0)
上一篇 2022年8月23日
下一篇 2022年8月23日

相关推荐

发表回复

登录后才能评论