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.
- 題目大意:給定n個二維平面上的點,求出這n個點當中最多有多少個點在同一直線上。
- 解題思路:每次取定一個點p1,然后求出p1與其他的n-1個點的斜率,並統計斜率相同的數目,取最大值即可。
- 具體實現:
#include <iostream>
#include <map>
#include <climits>
using namespace std;
struct Point {
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
class Solution {
public:
int maxPoints(vector<Point> &points) {
int maxNum =0;
int size = points.size();
int i,j;
if(size <=2) //如果點的個數小於3個,則最大數目為點的個數
return size;
for(i=0;i<size;i++)
{
int cnt =0;
map<double,int> mp;
for(j=0;j<size;j++)
{
if(i==j)
continue;
if(points[i].x == points[j].x && points[i].y == points[j].y)
{
cnt++;
continue;
}
//注意當直線與y軸平行的情況
double slope = points[i].x == points[j].x ? INT_MAX : (double)(points[j].y - points[i].y)/(points[j].x - points[i].x);
mp[slope]++;
}
if(mp.size()==0) //防止mp為空時,下面的for循環不執行
mp[INT_MIN] =0;
map<double,int>::iterator it = mp.begin();
for(;it!=mp.end();it++)
{
if(it->second+ cnt > maxNum)
maxNum = it->second +cnt;
}
}
return maxNum+1;
}
};
int main(int argc, char *argv[])
{
vector<Point> points;
Point point[3];
int i=0;
for(i=0;i<3;i++)
{
point[i].x = 1;
point[i].y= 1;
points.push_back(point[i]);
}
Solution solution;
cout<<solution.maxPoints(points);
return 0;
}
這里要注意3個地方:
1)如果點的個數小於3個,則最大數目為點的個數;
2)考慮重復點的情況,重復點是無法計算斜率的;
3)考慮直線與y軸平行時,斜率為無窮大的情況。
