题目
Given
n
points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路
这道题交了N遍才过。
maxPoints1:是O(n^3)的暴力法,枚举不同的两点,确定一条直线,然后对所有点进行点积判断是否共线(点积为0),共线则累加。超时()
maxPoints2:枚举一个点,再枚举另一个点,只需记录这两点斜率是否出现过,用map保存
注意问题
这题比较容易出错的是1、两个相同点,是算两次,因此在枚举的时候遇到相同的点时,要记录改点的重复次数
2、对于斜率不能表示的直线(两点的x值相同),需要单独记录这些点
3、应该用unordered_map,它的效率比map更高
代码
class Solution{
public:
double EPS;
int maxPoints(vector<Point> &points)
{
EPS = 1e-6;
return maxPoints2(points);
}
bool is_in_a_line(Point &p1,Point &p2,Point &p0)
{
if (fabs((p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y))<EPS)
return true;
else
return false;
}
int maxPoints1(vector<Point> &points)
{
//enumerate the line,then for every point tell if it is on this line
//two possibility:
//1.p1 equls p2
//2.p1 not equls p3
int max_np=0;
for(vector<Point>::iterator p1=points.begin();p1!=points.end();++p1)
for(vector<Point>::iterator p2=p1+1;p2!=points.end();++p2)
{
if (!(p1->x==p2->x && p1->y==p2->y))
{
int np =0;
for(vector<Point>::iterator p3=points.begin();p3!=points.end();++p3)
{
if (is_in_a_line(*p1,*p2,*p3) ) np++;
}
if (np>max_np) max_np = np;
}
else{
int np =0;
for(vector<Point>::iterator p3=points.begin();p3!=points.end();++p3)
{
if (p1->x==p2->x && p1->y==p2->y) np++;
}
if (np>max_np) max_np = np;
}
}
return max_np;
}
int maxPoints2(vector<Point> &points)
{
map<double,int> slope_map;
int max_np=0;
for(vector<Point>::iterator p1=points.begin();p1!=points.end();++p1)
{
slope_map.clear();
int points_of_vertical_line = 0;
int same_points = 0;
int cur_max_num=0;
for(vector<Point>::iterator p2=points.begin();p2!=points.end();++p2)
{
if (!(p1->x==p2->x && p1->y==p2->y))
{
//discuss the vetical line
if (p1->x==p2->x)
points_of_vertical_line ++;
else {
double slope = (p2->y - p1->y) * 1.0 / ( p2->x - p1->x );
/*if (slope_map.find(slope) == slope_map.end())
slope_map.insert(pair<double,int>(slope,1));
else*/
slope_map[slope]++;
if (slope_map[slope] >cur_max_num) cur_max_num = slope_map[slope];
}
}
else
same_points ++;
/* cur_max_num = points_of_vertical_line ;
for(map<double,int>::iterator it=slope_map.begin();it!=slope_map.end();++it)
if(it->second > cur_max_num) cur_max_num = it->second;*/
if (points_of_vertical_line>cur_max_num) cur_max_num = points_of_vertical_line;
}
if (same_points + cur_max_num>max_np) max_np =same_points + cur_max_num;
}
return max_np;
}
};
疑问
做这题最后也是参考的标准答案再写的,但是心里很疑惑 存储浮点数的时候,容器会不会出精度问题呢?unordered_map我觉得应该不会,实现机制是Hash,但是map呢?欢迎讨论