3.max-points-on-a-line 直线上的最多点

我不是女神ヾ 2022-06-06 07:20 315阅读 0赞

题目描述

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

给定一个二维平面上的n个点,找到一条直线上面的点最多,求得这个直线上的点的数目

题目解析

这个题目如果用暴力遍历的想法去做,本身并不难思考,难点在于将各种情况都考虑好。

先说一下我的遍历的方法是:

双层循环,外循环是循环每一个点,内循环是从外循环遍历的点后面一个点开始 循环到最后一个点。

每次循环,计算斜率,保存在map容器中,斜率相同时,map.second++。

这样循环的原因是:

因为两点确定一条直线,外循环保证的是,必须通过这个外循环遍历的这个点,其他点上的斜率,如果斜率相同自然是在同一条直线上的。

内循环 从外循环遍历的后一个点开始的原因是,如果需要经过前面的点的线,在前面外循环遍历时,已经记录了正确答案,比如给定 (0,0) (1,1) (2,2)外循环计算了(0,0) 有两个点相同斜率了之后,再遍历(1,1)时,就不需要再去把(0,0)再计算一遍,尽管在计算(1,1)时并不是正确的。

不过这样遍历明显不是最好的方法。

需要考虑的特殊情况:

1、平面中给出的只有一个点

2、为竖直的线,无法计算斜率,单独拿出来计算

3、重合的点

代码如下:

  1. /**
  2. * Definition for a point.
  3. * struct Point {
  4. * int x;
  5. * int y;
  6. * Point() : x(0), y(0) {}
  7. * Point(int a, int b) : x(a), y(b) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int maxPoints(vector<Point> &points)
  13. {
  14. if (points.size() < 3) return points.size();
  15. int start = 0;
  16. int max = 0;
  17. for (start = 0; start < points.size(); start++)
  18. {
  19. map<float, int> tmpMap;
  20. int perp = 0;
  21. int dup = 0;
  22. int tmpmax = 0;
  23. for (int i = start + 1; i < points.size(); i++)
  24. {
  25. int tmpx = points[i].x - points[start].x;
  26. int tmpy = points[i].y - points[start].y;
  27. if (0 == tmpx && 0 == tmpy)
  28. {
  29. dup++;
  30. }
  31. else if (0 == tmpx)
  32. {
  33. perp++;
  34. }
  35. else
  36. {
  37. float tmpSlope = (float)tmpy / tmpx;
  38. map<float, int>::iterator ite = tmpMap.find(tmpSlope);
  39. if (ite == tmpMap.end())
  40. {
  41. tmpMap.insert(make_pair(tmpSlope, 1));
  42. tmpmax = (0 == tmpmax) ? 1 : tmpmax;
  43. }
  44. else
  45. {
  46. ite->second++;
  47. tmpmax = (tmpMap[tmpSlope] > tmpmax) ? tmpMap[tmpSlope] : tmpmax;
  48. }
  49. }
  50. }
  51. tmpmax = (perp > tmpmax) ? perp : tmpmax;
  52. tmpmax += dup;
  53. max = (tmpmax > max) ? tmpmax : max;
  54. //if (max > points.size() - start) break;
  55. }
  56. return max + 1;
  57. }
  58. };

发表评论

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

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

相关阅读