Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Input: [[1,1],[2,2],[3,3]] Output: 3Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] Output: 4
#if 1
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
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) {
if (points.size() <= 0)
return 0;//点集为空
if (points.size() == 1)
return 1;//点集中只有一个点
int res = 0;//定义好结果
for (int i = 0; i<points.size(); i++) {//i为当前参考点
int vcnt = 0, dup = 0, curmax = 1;//垂直线的点,重合的点,当前共线的点的最大值
double delta_x = 0, delta_y = 0, k = 0.0;
map<double, int>mp;//哈希表存储相同斜率的点的数量
for (int j = 0; j<points.size(); j++) {
if (j != i) {
delta_x = points[i].x - points[j].x;
delta_y = points[i].y - points[j].y;
if (delta_x == 0 && delta_y == 0) {//重合点
dup++;
}
else if (delta_x == 0) {//垂直线上的点
if (vcnt == 0)
vcnt = 2;
else vcnt++;
curmax = max(vcnt, curmax);
}
else {
k = delta_y / delta_x;
if (mp[k] == 0)
mp[k] = 2; //斜率为k的数个数
else mp[k]++;
curmax = max(mp[k], curmax);
}
}
}
res = max(res, curmax + dup);//重合点要加载结果中
}
return res;
}
};
int main()
{
Point p1(1, 1);
Point p2(2, 2);
Point p3(3, 3);
Point p4(4, 4);
Point p5(5, 5);
Point p6(1, 2);
Point p7(1, 3);
Point p8(1, 4);
Point p9(2, 1);
Point p10(3, 1);
vector<Point> v;
v.push_back(p1);
v.push_back(p5);
v.push_back(p6);
v.push_back(p2);
v.push_back(p7);
v.push_back(p4);
v.push_back(p8);
v.push_back(p9);
v.push_back(p3);
v.push_back(p10);
Solution s;
cout<<s.maxPoints(v)<<endl;
return 0;
}
#endif