问题:
给定一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。
示例 1:
输入:points = [[1,1],[2,2],[3,3]]
输出:3
示例 2:
输入:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出:4
提示:
1 <= points.length <= 300
points[i].length == 2
-104 <= xi, yi <= 104
points 中的所有点 互不相同
解答思路:
以下是使用 Java 解决此问题的代码:
import java.util.HashMap;
import java.util.Map;public class MaxPointsOnALine {public int maxPoints(int[][] points) {int max = 0;for (int i = 0; i < points.length; i++) {Map<String, Integer> slopeCount = new HashMap<>();int samePoints = 1;int maxLocal = 0;for (int j = i + 1; j < points.length; j++) {if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {samePoints++;continue;}int dx = points[j][0] - points[i][0];int dy = points[j][1] - points[i][1];int gcd = gcd(dx, dy);dx /= gcd;dy /= gcd;String slope = dx + "_" + dy;slopeCount.put(slope, slopeCount.getOrDefault(slope, 0) + 1);maxLocal = Math.max(maxLocal, slopeCount.get(slope));}max = Math.max(max, maxLocal + samePoints);}return max;}public int gcd(int a, int b) {if (b == 0) {return a;}return gcd(b, a % b);}public static void main(String[] args) {int[][] points = {{1, 1}, {2, 2}, {3, 3}};MaxPointsOnALine solution = new MaxPointsOnALine();System.out.println(solution.maxPoints(points)); }
}
这个解决方案的基本思路是:对于每个点,计算它与其他点的斜率。为了避免精度问题,我们将斜率化简为最简形式(通过求分子和分母的最大公约数来化简)。然后,我们使用一个哈希表来记录每个斜率出现的次数。最后,我们找出每个点对应的最大斜率出现次数,并加上与该点重合的点的个数,更新全局的最大点数。
(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)