题解 | #直线上的牛# java
直线上的牛
https://www.nowcoder.com/practice/58ff4047d6194d2ca4d80869f53fa6ec
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param points int整型二维数组 * @return int整型 */ public int maxPoints (int[][] points) { // write code here int n = points.length; if (n <= 2) { return n; } int res = 0; for (int i = 0; i < n; i++) { Map<String, Integer> slopeCount = new HashMap<>(); int samePoints = 1; for (int j = i + 1; j < n; j++) { if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) { samePoints++; continue; } String slope = calculateSlope(points[i], points[j]); slopeCount.put(slope, slopeCount.getOrDefault(slope, 0) + 1); } int maxPointsOnLine = samePoints; for (Map.Entry<String, Integer> entry : slopeCount.entrySet()) { maxPointsOnLine = Math.max(maxPointsOnLine, entry.getValue() + samePoints); } res = Math.max(res, maxPointsOnLine); } return res; } private String calculateSlope(int[] point1, int[] point2) { if (point1[0] == point2[0]) { return "inf"; } else { return String.valueOf((double) (point2[1] - point1[1]) / (point2[0] - point1[0])); } } }
Java语言
该题考察的知识点是数学和哈希表的使用。
代码实现了通过计算斜率来判断点是否共线,并返回共线点的最大数量。算法遍历每个点,并使用哈希表 slopeCount
统计该点与其他点组成的直线的斜率出现的次数。然后,遍历哈希表,找到出现次数最多的斜率,并将其加上重复点的数量作为共线点的最大数量。
通过计算点之间的斜率来判断点是否在同一条直线上,并统计每个斜率出现的次数。最后,找出最多的重复点,并返回共线点的最大数量。