https://oj.leetcode.com/problems/max-points-on-a-line/
http://blog.csdn.net/linhuanmars/article/details/21060933
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ public class Solution { public int maxPoints(Point[] points) { { if (points == null || points.length == 0) return 0; int max = 1; for (int i = 0 ; i < points.length - 1 ; i ++) { // 对于该点,使用一个map保存其余点的斜率 Map<Double, Integer> map = new HashMap<>(); int samepoints = 0; // Number of same point. int x0 = 1; // Number of points with ratio +oo for (int j = i + 1 ; j < points.length ; j ++) { if (points[i].x == points[j].x && points[i].y == points[j].y) samepoints ++; else if (points[j].x == points[i].x) x0 ++; else { // 需要特意比对 ratio 为0 的情况是因为double 有 +0.0d 和 -0.0d double ratio = (points[i]. y == points[j].y) ? 0d : (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); Integer count = map.get(ratio); if (count == null) count = 1; count ++; map.put(ratio, count); } } max = Math.max(max, x0 + samepoints); for (int count : map.values()) max = Math.max(max, count + samepoints); } return max; } }