Skip to content

Commit ece2d20

Browse files
committed
3
1 parent 46cec25 commit ece2d20

File tree

1 file changed

+31
-20
lines changed

1 file changed

+31
-20
lines changed

MaxPointsOnALine/MaxPointsOnALine.cpp

+31-20
Original file line numberDiff line numberDiff line change
@@ -32,35 +32,46 @@ class Solution {
3232
int result = 2;
3333
sort(points.begin(), points.end());
3434
for (int i = 0; i < n; i++) {
35-
int dup = 1;
36-
while (i + 1 < n && points[i+1] == points[i]) {
37-
i++;
38-
dup++;
39-
}
40-
result = max(result, dup);
41-
if (i + 1 == n) {
42-
return result;
43-
}
44-
vector<double> slopes;
35+
vector<pair<int, int>> slopes;
36+
int count = 0;
4537
for (int j = i + 1; j < n; j++) {
46-
if (points[j].x == points[i].x) {
47-
slopes.push_back(numeric_limits<double>::max());
38+
int x = points[i].x - points[j].x;
39+
int y = points[i].y - points[j].y;
40+
int z = gcd(x, y);
41+
if (z != 0) {
42+
x /= z, y /= z;
43+
}
44+
if (x == 0 && y == 0) {
45+
count++;
4846
} else {
49-
slopes.push_back((double)(points[j].y - points[i].y) / (points[j].x - points[i].x));
47+
slopes.push_back(make_pair(x, y));
5048
}
5149
}
50+
if (slopes.empty()) {
51+
result = max(result, count + 1);
52+
continue;
53+
}
5254
sort(slopes.begin(), slopes.end());
53-
int count = 1;
54-
result = max(result, dup + 1);
55-
for (int k = 1; k < slopes.size(); k++) {
56-
if (slopes[k] == slopes[k-1]) {
57-
count++;
55+
int curr = 2 + count;
56+
result = max(result, curr);
57+
for (int j = 1; j < slopes.size(); j++) {
58+
if (slopes[j] == slopes[j-1]) {
59+
curr++;
5860
} else {
59-
count = 1;
61+
curr = 2 + count;
6062
}
61-
result = max(result, count + dup);
63+
result = max(result, curr);
6264
}
6365
}
6466
return result;
6567
}
68+
69+
int gcd(int a, int b) {
70+
while (b != 0) {
71+
int t = b;
72+
b = a % b;
73+
a = t;
74+
}
75+
return a;
76+
}
6677
};

0 commit comments

Comments
 (0)