-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmax_points_on_a_line.cpp
More file actions
47 lines (37 loc) · 1.04 KB
/
max_points_on_a_line.cpp
File metadata and controls
47 lines (37 loc) · 1.04 KB
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
class Solution {
public:
int maxPoints(vector<Point> &points) {
if (points.size() <= 2) {
return points.size();
}
int max_points = INT_MIN;
map<double, int> lines;
for (int i = 0; i < (points.size() - 1); ++i) {
int same_points = 0;
int _max_points = 1;
lines.clear();
for (int j = i + 1; j < points.size(); ++j) {
int x = points[i].x - points[j].x;
int y = points[i].y - points[j].y;
double slope = numeric_limits<double>::infinity(); // 偷懒的做法
if ((0 ==x) && (0 == y)) {
++same_points;
}
else {
if (y != 0) {
slope = (double)x / (double)y;
}
int count = (lines.find(slope) != lines.end()) ? lines[slope] + 1: 2;
lines[slope] = count;
if (_max_points < count) {
_max_points = count;
}
}
}
if (max_points < (_max_points + same_points)) {
max_points = _max_points + same_points;
}
}
return max_points;
}
};