Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
每次选择一个点,和其他n - 1个点,进行判断,统计最多的。double computeSlope(Point a, Point b) { double slope; if (a.x == b.x) { return Double.MAX_VALUE; } else { double yDiff = (double)(a.y - b.y); double xDiff = (double)(a.x - b.x); slope = yDiff/xDiff; return slope; } } public int maxPoints(Point[] points) { if (points == null || points.length == 0) { return 0; } int len = points.length; if (len <= 2) { return len; } int max = 1; Map<Double, Integer> map = new HashMap<Double, Integer>(); for (int i = 0; i < len; i++) { map.clear(); int tempMax = 1; int equal = 0; for (int j = 0;j < len; j++) { if (i != j) { if (points[i].x == points[j].x && points[i].y == points[j].y) { equal++; } else { double slope = computeSlope(points[i], points[j]); if (!map.containsKey(slope)) { if (tempMax == 1) { tempMax = 2; } map.put(slope, 1); } else { int temp = map.get(slope); if (temp + 2 > tempMax) { tempMax = temp + 2; } map.put(slope, temp + 1); } } } } if (max < tempMax + equal) { max = tempMax + equal; } } return max; }
Max Points on a Line,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010378705/article/details/35815077