LeetCode刷题笔记(穷举):max-points-on-a-line

向右看齐 2022-05-31 01:35 253阅读 0赞

  • 转载请注明作者和出处:http://blog.csdn.net/u011475210
  • 代码地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
  • 刷题平台:https://www.nowcoder.com/ta/leetcode
  • 题  库:Leetcode经典编程题
  • 编  者:WordZzzz

    • 题目描述
    • 解题思路
    • C版代码实现

题目描述

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

给定2D平面上的n个点,找出位于同一直线上的最大点数。

解题思路

两点确定一条直线,同时,对于斜率不为零的直线,都有y=kx+b。对于重复点,肯定也算是共线,所以,我们首先计算重复点的个数,然后计算斜率为0时共线的点个数,最后再计算其他斜率下共线的点的个数。

需要两重循环,第一重循环遍历起始点a,第二重循环遍历剩余点b。

  • 如果a和b重合,duplicate累加;
  • 如果a和b不重合,且两者斜率为0,则numVertical累加;
  • 如果a和b不重合,且两者斜率不为零,则计算斜率并计入map中,同时更新map中对应值;
  • 内循环结束后,返回max(local + duplicate, numVertical + duplicate)与之前的最大值res的最大值,local和numVertical算是不同斜率下的最大值;
  • 外循环结束后,返回res。

C++版代码实现

  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. if(points.size() <= 2)
  14. return points.size();
  15. int res = 0;
  16. for(int i = 0; i < points.size() - 1; ++i){
  17. unordered_map<double, int> map;
  18. int numVertical = 0, local = 1, duplicate = 0;
  19. for(int j = i + 1; j < points.size(); ++j)
  20. if(points[i].x == points[j].x)
  21. if(points[i].y == points[j].y) //重复点
  22. duplicate++;
  23. else //垂直点
  24. numVertical == 0 ? numVertical = 2 : numVertical++;
  25. else {
  26. double slope = (points[i].y - points[j].y) * 1.0 / (points[i].x - points[j].x);
  27. map[slope] == 0 ? map[slope] = 2 : map[slope]++;
  28. local = max(local, map[slope]);
  29. }
  30. local = max(local + duplicate, numVertical + duplicate);
  31. res = max(res, local);
  32. }
  33. return res;
  34. }
  35. };

系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

发表评论

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

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

相关阅读

    相关 52LeetCode_LeetCode手册

    虽然刷题一直饱受诟病,不过不可否认刷题确实能锻炼我们的编程能力,相信每个认真刷题的人都会有体会。现在提供在线编程评测的平台有很多,比较有名的有 hihocoder,LintCo

    相关 LeetCode笔记

    [23. Merge k Sorted Lists][] > 要点: > > 1. 学会数据结构PriorityQueue(优先队列)的用法, 通过给优先队列传入自定义