[leetcode]max points on a line

题目描述

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

暴力法,注意相同的点和x坐标相等的点(斜率无穷大)

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

* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/

public class {
public int maxPoints(Point[] points){
if(points.length <= 2) return points.length;

int result = 0;

for(int i = 0; i < points.length; i++){
//key为斜率,value为点数
HashMap<Double, Integer> map = new HashMap<>();
//x坐标相等的点的数量
int samex = 1;
//记录相同点
int samep = 0;

for(int j = 0; j < points.length; j++){
if(j != i){
if((points[j].x == points[i].x) && (points[j].y == points[i].y)){
samep++;
}

if(points[j].x == points[i].x){
samex++;
continue;
}
double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);

if(map.containsKey(k)){
map.put(k, map.get(k) + 1);
}else{
map.put(k, 2);
}
result = Math.max(result, map.get(k) + samep);
}
}

result = Math.max(result, samex);
}
return result;
}
}