LeetCode149—Max Points on a Line

£神魔★判官ぃ 2022-07-15 09:21 206阅读 0赞

原题

原题链接

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Subscribe to see which companies asked this question


分析

O(n2)复杂度,每个点都要考虑三种情况:

1.普通的点,在同一直线上满足slope=y1−y2x1−x2相等。
2.跟当前点重合的点。
3.跟当前点在同一条直线且平行于y轴的点。

最后最大值可能有两种情况:

  1. 与点p重合的点 + 与点p斜率相同
  2. 与点p重合的点 + 与点p斜率相同且平行与y轴

返回结果最后+1表示包含点p即可。

代码

  1. class Solution {
  2. private:
  3. /*计算斜率*/
  4. double Slope(Point&a ,Point&b)
  5. {
  6. return (b.y-a.y)*1.0/(b.x-a.x);
  7. }
  8. public:
  9. int maxPoints(vector<Point>& points)
  10. {
  11. if(points.size()<2)
  12. return points.size();
  13. int res=0;
  14. for(int i=0;i<points.size();i++)
  15. {
  16. int local=0;//局部最优
  17. int same=0;//与当前点p重合的点
  18. int infinity=0;//与当前点p平行于Y轴的点
  19. unordered_map<double,int>count;//与当前点p斜率相同的点
  20. for(int j=i+1;j<points.size();j++)
  21. {
  22. if(points[i].x==points[j].x&&points[i].y==points[j].y)
  23. {
  24. ++same;
  25. }
  26. else if(points[i].x==points[j].x)
  27. {
  28. ++infinity;
  29. }
  30. else
  31. {
  32. double slope= Slope(points[i],points[j]);
  33. count[slope]++;
  34. }
  35. }
  36. int tmp=0;
  37. for(auto it = count.begin();it!=count.end();it++)
  38. {
  39. tmp=max(tmp,it->second);
  40. }
  41. local=max(tmp+same,same+infinity);//局部最优
  42. res=max(local,res);//全局最优
  43. }
  44. return res+1;//包含本身
  45. }
  46. };

发表评论

表情:
评论列表 (有 0 条评论,206人围观)

还没有评论,来说两句吧...

相关阅读