forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
100 lines (76 loc) · 2.26 KB
/
main.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
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
90
91
92
93
94
95
96
97
98
99
100
/// Source : https://leetcode.com/problems/max-points-on-a-line/
/// Author : liuyubobobo
/// Time : 2017-07-17
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Definition for a point.
struct Point {
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
/// Using Hash Map
/// Using string to record the slopes
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
class Solution {
public:
int maxPoints(vector<Point>& points) {
if( points.size() <= 1 )
return points.size();
int res = 1;
for( int i = 0 ; i < points.size() ; i ++ ){
unordered_map<string, int> record;
int samePoint = 0;
for( int j = 0 ; j < points.size() ; j ++ ){
if( points[i].x == points[j].x && points[i].y == points[j].y )
samePoint ++;
else
record[getPairStr(slope(points[j], points[i]))]++;
}
res = max(res, samePoint); // In case the record is empty and all the points are in the same point.
for( unordered_map<string,int>::iterator iter = record.begin() ; iter != record.end() ; iter ++ )
res = max( res , iter->second + samePoint );
}
return res;
}
private:
pair<int,int> slope( const Point &pa, const Point &pb ){
int dy = pa.y - pb.y;
int dx = pa.x - pb.x;
if( dx == 0 )
return make_pair(1,0);
if( dy == 0 )
return make_pair(0,1);
int g = gcd( abs(dy), abs(dx) );
dy /= g;
dx /= g;
if( dx < 0 ){
dy = -dy;
dx = -dx;
}
return make_pair( dy , dx );
}
int gcd( int a , int b ){
if( a < b )
swap( a , b );
if( a % b == 0 )
return b;
return gcd( b , a%b );
}
string getPairStr( const pair<int,int> p){
return to_string(p.first) + "/" + to_string(p.second);
}
};
int main() {
vector<Point> pvec1;
pvec1.push_back( Point(1, 1) );
pvec1.push_back( Point(1, 1) );
//pvec1.push_back( Point(2, 3) );
//pvec1.push_back( Point(3, 3) );
cout<<Solution().maxPoints(pvec1)<<endl;
return 0;
}