Max Points on a Line (Hard)

Description

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Analysis

2维空间内若干点,求在一条直线上的最多的点的个数。既然点都在一条直线上,
那么它们两点之间的斜率一定是相等的。因此,我们可以循环遍历每个点,以该点为原点,
计算到其他各点的斜率。如果若干相等,则说明位于同一直线上。由于斜率是浮点数,我们可以使用
map来hash。同时也学到了unordered_map 这个东西。后者不会按照key值排序.

My Solution

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
//C++
/**
* 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 {
private:
bool issame(Point a,Point b){
if(a.x==b.x&&a.y==b.y)
return true;
return false;
}
private:
double getk(Point a,Point b){
double k = 1.0*(a.y-b.y)/(a.x-b.x);
return k;
}
public:
int maxPoints(vector<Point> &points) {
// map<double,int> mp;
unordered_map<double,int> mp;
int len = points.size(),ans = 0;
for(int i = 0;i<len;i++){
mp.clear();
int same = 0,total = 1;
for(int j = i+1;j<len;j++){
double k ;
if(this->issame(points[i],points[j])){
same++;
continue;
}
if(points[i].x!=points[j].x){
k = this->getk(points[i],points[j]);
}
else{
k = INT_MAX+0.0;
}
if(mp.find(k)!=mp.end()){
mp[k]++;
}
else{
mp[k]=2;
}
if(total<mp[k])
total = mp[k];
}
if(total+same>ans)
ans = total+same ;
}
return ans;
}
};