题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题解:
先取一个点,判断其他剩下的所有点是否在一条直线上,统计个数,如果该个数大于maximum,修改maximum,继续选取下一个点,do the same thing,直到全部点遍历完。
/**
* Definition for a point.
* 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;
map<float, int> slopes;
for(int i = 0; i < points.size(); i++)
{
slopes.clear();
slopes[INT_MIN] = 0;
int duplicate = 1;
for(int j = 0; j < points.size(); j++)
{
if(i == j)
continue;
if(points[i].x == points[j].x && points[i].y == points[j].y)
{
duplicate++;
continue;
}
float slope = points[i].x == points[j].x ? INT_MAX : (float)(points[i].y - points[j].y)/(points[i].x-points[j].x);
slopes[slope]++;
}
for(auto iter: slopes)
{
if(iter.second + duplicate > maxNum)
maxNum = iter.second + duplicate;
}
}
return maxNum;
}
};