Go教程

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

本文主要是介绍[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;
    }
};
这篇关于[Google] LeetCode 1610 Maximum Number of Visible Points 极角排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!