LeetCode:Max Points on a Line

题目链接

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

分析:首先要注意的是,输入数组中可能有重复的点。由于两点确定一条直线,一个很直观的解法是计算每两个点形成的直线,然后把相同的直线合并,最后包含点最多的直线上点的个数就是本题的解。我们知道表示一条直线可以用斜率和y截距两个浮点数(垂直于x轴的直线斜率为无穷大,截距用x截距),同时还需要保存每条直线上的点(避免重复)。听起来就很麻烦,但是基于这个思想有一种简单的实现方式:

  • 以某点O为中心,计算它和其他点的斜率,如果有两个点A、B和O点形成的斜率相等,那么ABO三点是共线的,如果有多个点和O的斜率相等,那么这多个点和O也是共线的,因此我们可以求出包含O的所有直线中点数最多的直线,会得到一个最大共线点数k(O),如果和O点重复的点有n个(除了O本身),那么K(O) = K(O) + n。这一步的计算中,为了提高效率,我们可以用哈希表来保存某个斜率对应的点的数目。
  • 对数组中的每一个点i,按照第一步计算得到每个点最大点数K(i)
  • 从k(i)中选取最大的就是本题的解
  • 注意:为了避免重复计算,以数组中第i个点为中心时,只计算数组中它右边的所有点                                                                                                                  本文地址
 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         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         int len = points.size(), res = 1;
16         if(len == 0)return 0;
17         unordered_map<double, int> umap;
18         for(int i = 0; i < len; i++)
19         {
20             umap.clear();
21             int samePointNum = 0,tmpres = 1;
22             for(int j = i+1; j < len; j++)
23             {
24                 double slope = std::numeric_limits<double>::infinity();//斜率初始化为无穷大,我们视横坐标相同的两点间的斜率为无穷大
25                 if(points[i].x != points[j].x)
26                     slope = 1.0*(points[i].y - points[j].y) / (points[i].x - points[j].x);
27                 else if(points[i].y == points[j].y)
28                     {samePointNum++; continue;}
29                 int tmp;
30                 if(umap.find(slope) != umap.end())
31                     tmp = ++umap[slope];
32                 else 
33                 {
34                     umap.insert(unordered_map<double, int>::value_type(slope, 2));
35                     tmp = 2;
36                 }
37                 if(tmpres < tmp)tmpres = tmp;
38             }
39             if(res < tmpres + samePointNum)res = tmpres + samePointNum;
40         }
41         return res;
42     }
43 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3444086.html

转载于:https://www.cnblogs.com/TenosDoIt/p/3444086.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值