Problem: 149. 直线上最多的点数
思路
👨🏫 参考题解
💖 枚举直线 + 枚举统计
时间复杂度: O ( n 3 ) O(n^3) O(n3)
空间复杂度: O ( 1 ) O(1) O(1)
class Solution {public int maxPoints(int[][] points){int n = points.length;int ans = 1;for (int i = 0; i < n; i++){int[] a = points[i];// 点1for (int j = i + 1; j < n; j++){int[] b = points[j];// 点2int cnt = 2;for (int k = j + 1; k < n; k++){int[] c = points[k];// 枚举其他的点
// int s1 = (b[1] - a[1]) * (c[0] - b[0]);
// int s2 = (c[1] - b[1]) * (b[0] - a[0]);int s1 = (a[1] - b[1]) * (b[0] - c[0]);int s2 = (a[0] - b[0]) * (b[1] - c[1]);if (s1 == s2)cnt++;}ans = Math.max(cnt, ans);}}return ans;}
}
枚举直线 + 哈希表统计
class Solution {
// 枚举直线 + 哈希表统计public int maxPoints(int[][] points){int n = points.length, ans = 1;for (int i = 0; i < n; i++){Map<String, Integer> map = new HashMap<>();// 由当前点 i 发出的直线所经过的最多点数量int max = 0;int x1 = points[i][0], y1 = points[i][1];for (int j = i + 1; j < n; j++){int x2 = points[j][0], y2 = points[j][1];int xx = x1 - x2, yy = y1 - y2;int k = gcd(xx, yy);// 最大公约数String key = (xx / k) + "_" + (yy / k);// 化简map.put(key, map.getOrDefault(key, 0) + 1);// key 是斜率,value 是数量max = Math.max(max, map.get(key));}ans = Math.max(ans, max + 1);}return ans;}// 求最大公约数int gcd(int a, int b){return b == 0 ? a : gcd(b, a % b);}
}