您的位置:首页 > 其它

解题报告(LeetCode):Max Points on a Line

2015-12-12 01:50 369 查看
题目描述:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

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

思路一:

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

思路二:

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

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

代码:

class Solution {
public:
int maxPoints(vector<Point>& points) {
map<double,int> slope;           //建立斜率与出现次数的映射
if(points.size() <= 2)          //点的个数小于3时,直接返回点的个数
return points.size();
int n = points.size(),ans = 0;     //ans为最终结果
for(int i = 0; i < n - 1; i++)
{
int maxNum = 0;                //记录当前节点对应的斜率出现最多的次数
int same_x = 1;                //记录斜率不存在,即横坐标相等的情况
int samePoint = 0;             //记录重合的点
slope.clear();
for(int j = i + 1; j < n; j++)
{

if (i == j)
continue;
if (points[i].x == points[j].x && points[i].y == points[j].y)
{
samePoint++;
continue;
}
if (points[i].x == points[j].x)  //斜率不存在
{
same_x++;
continue;
}
double k = (double)(points[i].y-points[j].y)/(points[i].x-points[j].x);
if (slope.find(k) != slope.end())   //更新当前斜率出现的次数
slope[k]++;
else
slope[k] = 2;
}
for (map<double,int>::iterator it = slope.begin(); it != slope.end(); ++it)   //找出最大次数的斜率
same_x = max(same_x,it->second);
maxNum = same_x + samePoint;
ans = max(ans,maxNum);                  //与之前的最大值比较
}
return ans;
}
};


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



此博客中的内容均为原创或来自网络,不用做任何商业用途。欢迎与我交流学习,我的邮箱:lsa0924@163.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: