[LintCode] 最多有多少个点在一条直线上

时间:2023-03-08 22:10:10
 /**
* 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:
/**
* @param points an array of point
* @return an integer
*/
int maxPoints(vector<Point>& points) {
// Write your code here
unordered_map<float, int> slopes;
int maxp = , n = points.size();
for (int i = ; i < n; i++) {
slopes.clear();
int duplicate = ;
for (int j = i + ; j < n; j++) {
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]++;
}
maxp = max(maxp, duplicate);
for (auto slope : slopes)
if (slope.second + duplicate > maxp)
maxp = slope.second + duplicate;
}
return maxp;
}
};