-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxPointCollinear.h
73 lines (69 loc) · 2.04 KB
/
maxPointCollinear.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
//
// Created by so_go on 2019/6/19.
//
#ifndef SRC_MAXPOINTCOLLINEAR_H
#define SRC_MAXPOINTCOLLINEAR_H
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
class maxPointsCollinear {
public:
vector<int> calculateSlope(vector<int> p1, vector<int> p2){
int dx, dy, dd;
dx = p2[0] - p1[0];
dy = p2[1] - p1[1];
dd = __gcd(dx, dy);
// cout << dx << ' ' << dy << ' ' << dd << endl;
return vector<int>{dx / dd, dy / dd};
}
// 用分数保存斜率!!!
int maxPoints(vector<vector<int>>& points) {
int nPoints = points.size();
if(nPoints == 0){
return 0;
}
// cout << "num of Points: " << nPoints << endl;
vector<vector<float >> m(nPoints, vector<float>(nPoints, 0));
map<vector<int>, int> count;
vector<int> slope;
int max = 0, curMax = 0;
int duplicate = 0;
auto ptr = count.end();
int i = 0, j = 0;
for(i = 0; i < points.size(); i++){
count.clear();
curMax = 0;
duplicate = 0;
for(int j = 0; j < nPoints; j++){
if(points[i] != points[j]){
slope = calculateSlope(points[i], points[j]);
// cout << m[i][j] << ' ';
ptr = count.find(slope);
if(ptr == count.end()){
count.insert({slope, 1});
}
else{
ptr->second++;
}
}
else{
duplicate++;
}
}
// cout << endl;
for(auto ptr = count.begin(); ptr != count.end(); ptr++){
if(ptr->second > curMax){
curMax = ptr->second;
}
}
curMax += duplicate;
if(curMax > max){
// cout << curMax << endl;
max = curMax;
}
}
return max;
}
};
#endif //SRC_MAXPOINTCOLLINEAR_H