Leetcode 149. Max Points on a Line (Hard) (cpp)
Tag: Hash Table, Math
Difficulty: Hard
/*
149. Max Points on a Line (Hard)
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
*/
/**
* 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) {
if (points.size() < 3) return points.size();
int res = 0;
for (int i = 0; i < points.size(); i++) {
int p0_num = 1, k_max = 0;
unordered_map<double, int> mapping;
for (int j = i + 1; j < points.size(); j++) {
if (points[i].x == points[j].x && points[i].y == points[j].y) p0_num++;
else {
double k;
if (points[i].x == points[j].x) k = INT_MAX;
else k = double(points[i].y - points[j].y) / double(points[i].x - points[j].x);
k_max = max(k_max, ++mapping[k]);
}
}
res = max(res, k_max + p0_num);
}
return res;
}
};