1. 程式人生 > 實用技巧 >leetcode1610 可見點的最大數目

leetcode1610 可見點的最大數目

思路:

將點按照極角排序後,用滑動視窗法求解。

實現:

 1 class Solution
 2 {
 3 public:
 4     const double PI = acos(-1);
 5     int visiblePoints(vector<vector<int>>& points, int angle, vector<int>& location)
 6     {
 7         int cnt = 0;
 8         vector<double> v;
 9         for (auto& it: points)
10 { 11 if (it[0] == location[0] && it[1] == location[1]) 12 { 13 cnt++; continue; 14 } 15 double r = atan2(it[1] - location[1], it[0] - location[0]); 16 if (r < 0) r += 2 * PI; 17 r = r / PI * 180; 18
v.push_back(r); 19 } 20 sort(v.begin(), v.end()); 21 int n = v.size(); 22 for (int i = 0; i < n; i++) v.push_back(v[i] + 360); 23 int l = 0, r = 0, res = 0; 24 while (r < 2 * n) 25 { 26 while (r < 2 * n && v[r] - v[l] <= angle) r++;
27 res = max(res, r - l); 28 while (r < 2 * n && l <= r && v[r] - v[l] > angle) l++; 29 r++; 30 } 31 return res + cnt; 32 } 33 }