# Leetcode刷题面试题 16.14. 最佳直线

2 <= len(Points) <= 300
len(Points[i]) = 2

class Solution {
public int[] bestLine(int[][] points) {
return bestLineI(points);
//            return bestLineII(points);
}

//方法二：三层for循环
private int[] bestLineII(int[][] points) {
if (points.length < 3) return new int[]{0, 1};
int max = 0;
int[] res = new int[2];
for (int i = 0; i < points.length - 1; i++) {
for (int j = i + 1; j < points.length; j++) {
int nums = 2;
int dy = points[j][1] - points[i][1];
int dx = points[j][0] - points[i][0];
for (int k = j + 1; k < points.length; k++) {
int ky = points[k][1] - points[j][1];
int kx = points[k][0] - points[j][0];
//若等式相等，说明直线在一条直线上
if (dy * kx == dx * ky) {
nums++;
}
}
//求出经过i,j两点组成直线的所有点，并返回结果
if (nums > max) {
max = nums;
res[0] = i;
res[1] = j;
}
}
}
return res;
}

//方法一：使用hashMap缓存斜率
private int[] bestLineI(int[][] points) {
//保存经过一条直线上所有的点
List<Integer> res = new ArrayList<>();
for (int i = 0; i < points.length - 1; i++) {
Map<String, List<Integer>> map = new LinkedHashMap<>();
for (int j = i + 1; j < points.length; j++) {
int dx = points[j][0] - points[i][0];
int dy = points[j][1] - points[i][1];
int gcd = gcd(dx, dy);
String key = dx / gcd + ":" + dy / gcd;
List<Integer> list;
if (map.get(key) == null) {
//斜率key不存在，map中添加元素
list = new ArrayList<>();
map.put(key, list);
} else {
//因为只需要返回穿过直线的前两个点的编号，所以当斜率已经存在时，list追加j元素即可
list = map.get(key);
map.put(key, list);
}
if (list.size() > res.size()) {
res = list;
}
}
}
return new int[]{res.get(0), res.get(1)};
}

private int gcd(int x, int y) {
if (y == 0) return x;
return gcd(y, x % y);
}
}

02-14 3344
11-06 51
06-19 97
03-21 177
06-19 93
08-09 465
04-17 938
12-18