-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path149-Max Points on a Line.cpp
executable file
·51 lines (44 loc) · 1.38 KB
/
149-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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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() < 2) {
return points.size();
}
int maxNum = 0;
for (int i = 0; i < points.size(); ++i) {
int samePoint = 1;
int localMax = 0;
unordered_map<int, unordered_map<int, int>> mp;
for (int j = i + 1; j < points.size(); ++j) {
if (points[i].x == points[j].x && points[i].y == points[j].y) {
samePoint += 1;
continue;
}
int diffY = points[i].y - points[j].y;
int diffX = points[i].x - points[j].x;
int g = gcd(diffX, diffY);
if (g != 0) {
diffY /= g;
diffX /= g;
}
mp[diffX][diffY] += 1;
localMax = max(localMax, mp[diffX][diffY]);
}
maxNum = max(maxNum, localMax + samePoint);
}
return maxNum;
}
private:
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
};