解题报告(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.算法

解题思路:题目说的很是清楚,寻找二维点在一条直线上的最大数目。网络

思路一:ide

  首先想到的方式就是直接法,遍历每一个节点,一个节点下,遍历一遍,肯定一条直线后,再遍历一遍肯定这条直线上的次数,这样的话,时间复杂度就是O(n3)。感受在OJ上会跪,就不写了//不过看到刘斌的博客,貌似是能够AC的学习

思路二:spa

  既然直接法太复杂的话,咱们接着思考其余方法。我想到能够用直线的斜率k描述一条直线,把全部的点的直线搭配的斜率计算出来,存储起来,最后找到斜率出现最多的次数,就对应点最多的直线。code

  考虑使用map,创建斜率k和出现次数的映射,最后取出最大的次数便可。其中须要处理,两个点相等以及斜率不存在(即横坐标相等的状况)blog

代码:leetcode

 1 class Solution {
 2 public:
 3     int maxPoints(vector<Point>& points) {
 4         map<double,int> slope;           //创建斜率与出现次数的映射
 5         if(points.size() <= 2)          //点的个数小于3时,直接返回点的个数
 6             return points.size();
 7          int n = points.size(),ans = 0;     //ans为最终结果
 8         for(int i = 0; i < n - 1; i++)      
 9         {
10             int maxNum = 0;                //记录当前节点对应的斜率出现最多的次数
11             int same_x = 1;                //记录斜率不存在,即横坐标相等的状况
12             int samePoint = 0;             //记录重合的点
13             slope.clear();                
14             for(int j = i + 1; j < n; j++)   
15             {
16                 
17                   if (i == j)
18                       continue;    
19                   if (points[i].x == points[j].x && points[i].y == points[j].y) 
20                   {
21                     samePoint++;
22                     continue;
23                 }
24                   if (points[i].x == points[j].x)  //斜率不存在   
25                   {
26                       same_x++;
27                       continue;
28                   }
29                   double k = (double)(points[i].y-points[j].y)/(points[i].x-points[j].x);
30                   if (slope.find(k) != slope.end())   //更新当前斜率出现的次数
31                       slope[k]++;
32                   else
33                       slope[k] = 2;
34             }
35             for (map<double,int>::iterator it = slope.begin(); it != slope.end(); ++it)   //找出最大次数的斜率
36                 same_x = max(same_x,it->second);
37             maxNum = same_x + samePoint;
38             ans = max(ans,maxNum);                  //与以前的最大值比较
39         }         
40         return ans;
41     }
42 };
View Code

在leetcode上提交,能够AC,分析一下这个算法的复杂度,外层为两个循环,内层使用map求出最大值。时间复杂度为O(n2)。博客

此博客中的内容均为原创或来自网络,不用作任何商业用途。欢迎与我交流学习,个人邮箱:lsa0924@163.comit

相关文章
相关标签/搜索