您的位置:首页 > 其它

共线点Max Points on a Line

2014-08-26 20:56 302 查看
题目:

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

解析:

找到平面中共线点最大值,似乎蛮容易的,结果我WA了好几次。主要思路就是两点确定一条线,依次判断其余点是否在该线上,进行统计最大值。肯定有很多可以优化的,我也尝试了,结果画蛇添足了。以后有机会去看看别人的吧,肯定有好的算法的,本文中直接判断。

<pre name="code" class="cpp">int maxPoints(vector<Point> &points) {
int m_size = points.size();
if(m_size <= 2) return m_size;
int i_max = 0, i_temp = 0;
double k1, k2, b;
bool *flag = new bool[m_size];

for(int index1 = 0; index1 < m_size; index1++) //point1
{
int i_same = 0; //标记相同点数
for(int index2 = index1 + 1; index2 < m_size; index2++ ) //point2
{
//	if(flag[index2] == true) continue; //被识别过的点
k1 = points[index2].x - points[index1].x;
k2 = points[index2].y - points[index1].y;
if(k1 == 0 && k2 == 0)  //相同点不形成直线
{
i_same++;
continue;
}
b = points[index1].y * points[index2].x - points[index2].y * points[index1].x;
i_temp = 2;
for(int i = index2 + 1; i < m_size ; i++)
{
if(k1 * points[i].y == k2 * points[i].x + b)
i_temp++;
}
i_max = (i_temp + i_same > i_max) ? i_temp + i_same : i_max;
}
i_max = (i_same + 1 > i_max) ? i_same + 1 : i_max;
}
delete flag;
return i_max;
}



说明:

1.这个题要很考虑健壮性,包括一个点,均为相同点,重复项等,自己测试是可以考虑test1[(0,0)]; test2[(1,1),(1,1)] test3[(1,1),(1,1),(1,1)] test4[(1,1),(1,1),(1,2)]以及常规测试

2.为了方便看,省略了一些可以省略的{},但是觉得代码块其实还是有{}的好,一方面方便加代码另一方面自己容易查错

3.关于判读是否共线,使用了将每个相对常用的值计算出来,如k1,k2,b。其中k1=x2 - x1, k2 = y1 -y2,b = y1x2- y2x1. 此时直线为y*k1 = k2*x + b。算是部分优化吧

  别小看循环里的任何一个计算,尽可能的减少运算量,对于程序的时间消耗是会有质的改变的。(曾经处理图片数据的深切感受啊~~)

4.深知道这个程序还可以优化的,时间复杂度过高,三重循环。RunTime 92ms。。伤不起~~

自我反思:

刷这个题目,觉得自己考虑的太少了,很多情况都没有考虑,导致了WA,而过度想着优化时间也让自己很多疏忽程序原本的功能性要求,以后要注意!fighting~~

/**
* Definition for a point.
* struct Point {
*     int x;
*     int y;
*     Point() : x(0), y(0) {}
*     Point(int a, int b) : x(a), y(b) {}
* };
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: