-
Notifications
You must be signed in to change notification settings - Fork 213
/
MaxPointsOnALine.h
89 lines (85 loc) · 2.59 KB
/
MaxPointsOnALine.h
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Author: Matthew Jin, [email protected] : King, [email protected]
Date: Dec 03, 2014
Problem: Max Points On a Line
Difficulty: Easy
Notes:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution: 1. hashmap. Time: O(n^2), Space: O(n);
2. high precision.
*/
/**
* 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:
struct pt {
int dx, dy;
pt(){dx = 0; dy = 0;}
pt(int x, int y) {
int g = gcd(abs(x), abs(y));
if (x==0 && y==0) dx=0,dy=0;
else if(x==0) dx=0,dy=1;
else if(y==0) dx=1,dy=0;
else if(y>0) dx=x/g,dy=y/g;
else if(y<0) dx=-x/g,dy=-y/g;
}
int gcd(int a, int b) {
if(b == 0) return a;
else return gcd(b, a%b);
}
bool operator==(const pt &b) const {
return dx == b.dx && dy == b.dy;
}
bool operator<(const pt &b) const {
if(dx == b.dx) return dy < b.dy;
return dx < b.dx;
}
};
int maxPoints_1(vector<Point> &points) {
int N = points.size(), res(0);
unordered_map<double, int> m;
for (int i =0; i < N; ++i) {
m.clear();
int ss(1), sp(0);// ss: points with same slope, sp: same points.
for (int j = i + 1; j < N; ++j) {
double slope = std::numeric_limits<double>::infinity();
if (points[i].x != points[j].x) {
slope = 1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);
} else if (points[i].y == points[j].y) {
++sp; continue;
}
int tmp = 0;
if(m.find(slope) != m.end()) tmp = ++m[slope];
else tmp = m[slope] = 2;
ss = max(ss, tmp);
}
res = max(res, ss + sp);
}
return res;
}
int maxPoints_2(vector<Point> &points) {
int N = points.size(), res(0);
pt zero(0,0);
map<pt, int> m;
for (int i=0; i < N; ++i) {
m.clear();
int ss(0), sp(0);
for (int j = 0; j < N; ++j) {
pt slope(points[i].x-points[j].x, points[i].y-points[j].y);
if (slope == zero) ++sp;
else {
ss = max(ss, ++m[slope]);
}
}
res = max(res, ss + sp);
}
return res;
}
};