-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path149.直线上最多的点数.java
73 lines (69 loc) · 1.85 KB
/
149.直线上最多的点数.java
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
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/*
* @lc app=leetcode.cn id=149 lang=java
*
* [149] 直线上最多的点数
*/
// @lc code=start
class Solution {
int n;
static class Slope {
int dx, dy;
Slope(int dy, int dx){
this.dx = dx;
this.dy = dy;
}
}
public int maxPoints(int[][] points) {
if(points.length <= 2){
return points.length;
}
n = points.length;
int max = 2;
for(int i = 0;i < n;++i){
Map<Slope, Integer> map = new TreeMap<>((a, b)->{
if(a.dx == b.dx && a.dy == b.dy){
return 0;
}
if(a.dx == b.dx){
return a.dy - b.dy;
}
return a.dx - b.dx;
});
for(int j = i + 1;j < n;++j){
int dx = points[j][0] - points[i][0];
int dy = points[j][1] - points[i][1];
if(dx < 0){
dy *= -1;
dx *= -1;
}
if(dx == 0){
dy = Integer.MAX_VALUE;
} else if(dy == 0){
dx = 0;
}else {
int gcd = gcd(Math.abs(dx), Math.abs(dy));
dx /= gcd;
dy /= gcd;
}
Slope curSlope = new Slope(dy, dx);
int previousCnt = map.getOrDefault(curSlope, 1);
map.put(curSlope, previousCnt + 1);
max = Math.max(max, previousCnt + 1);
}
}
return max;
}
private int gcd(int a, int b){
int tmp = 0;
while(a % b != 0){
tmp = b;
b = a % b;
a = tmp;
}
return b;
}
}
// @lc code=end