题目:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:固定一个点,遍历其余点,期间用一个HashMap记录两点斜率和斜率次数,求出局部最大值;然后再固定另一点,遍历其余点,.........,即两层循环,内层循环求出局部最大值,外层循环更新全局最大值。需要注意:1. 点重叠的情况 2. 直线垂直于x轴的情况 3. 正常情况 4. 斜率为-0.0的情况
Java代码:
public int maxPoints(Point[] points) { if (points.length <= 2) { return points.length; } int max = 0; float k = 0f; for (int i = 0; i < points.length-1; i++) { // 全局最大值 HashMap<Float, Integer> hm = new HashMap<Float, Integer>(); hm.put(Float.MAX_VALUE, 0); int repoint = 0; for (int j = i+1; j < points.length; j++) { // 局部最大值,固定一个点 if (points[i].x == points[j].x && points[i].y == points[j].y) { // 点重合 repoint++; } else if (points[i].x == points[j].x) { //垂直x轴 hm.put(Float.MAX_VALUE, hm.get(Float.MAX_VALUE)+1); } else { k = (float)(points[i].y - points[j].y)/(points[i].x - points[j].x); //正常情况 if (k == -0.0) { // 出现-0.0 k = 0f; } if (!hm.containsKey(k)) { hm.put(k, 1); } else { hm.put(k, hm.get(k)+1); } } } for (Float d : hm.keySet()) { if(hm.get(d)+repoint+1 > max) { max = hm.get(d)+repoint+1; } } } return max; }
时间: 2024-10-13 16:20:15