题目链接:https://leetcode-cn.com/problems/maximum-number-of-visible-points/
题意
平面上有n个点,你从一个固定点去观察,视野角度是angle,求最多同时观察到多少个点,点不会被其它点遮挡
题解
将所有点极角排序,然后复制双倍数组处理循环,枚举左端点滑动窗口维护右端点即可
复杂度
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn),主要复杂度在排序
注意特判和原点重合的点
code
class Solution
{
public:
int visiblePoints(vector<vector<int>> &points, int angle, vector<int> &location)
{
int n = points.size();
double an = angle * pi / 180.0;
vector<double> angs;
int eq = 0;
for (int i = 0; i < n; i++)
{
if (points[i] == location)
{
eq++;
continue;
}
int x = points[i][0] - location[0];
int y = points[i][1] - location[1];
angs.push_back(atan2(y, x));
}
sort(angs.begin(), angs.end());
n = angs.size();
for (int i = 0; i < n; i++)
angs.push_back(angs[i] + 2.0 * pi);
int ri = 0;
int ans = 0;
const double eps = 1e-8;
for (int le = 0; le < n; le++)
{
while (ri < le + n && angs[ri] - angs[le] <= an + eps)
ri++;
ans = max(ans, ri - le);
}
return ans + eq;
}
};