-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMax_Points_on_a_Line.cpp
33 lines (32 loc) · 1.11 KB
/
Max_Points_on_a_Line.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Given n points on a 2D plane, find the maximum number of points
// that lie on the same straight line.
class Solution {
public:
int maxPoints(vector<Point> &points) {
unordered_map<float, int> mp;
int maxNum = 0;
for (int i = 0; i < points.size(); i++) {
mp.clear();
mp[INT_MIN] = 0; // axis y
int duplicate = 1;
for (int j = 0; j < points.size(); j++) {
if (j == i)
continue;
if (points[i].x == points[j].x && points[i].y == points[j].y) {
duplicate++;
continue;
}
float k = (points[i].x == points[j].x) ? INT_MAX : (float)\
(points[j].y - points[i].y) / (points[j].x - points[i].x);
mp[k]++;
}
unordered_map<float, int>::iterator it = mp.begin();
for (; it != mp.end(); it++) {
if (it->second + duplicate > maxNum) {
maxNum = it->second + duplicate;
}
}
}
return maxNum;
}
};