[LintCode] Max Points on a Line

428 查看

Problem

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Example

Given 4 points: (1,2), (3,6), (0,0), (1,3).
The maximum number is 3.

Note

建立一个斜率对应point个数的HashMap。
两次循环对points中第i个和第j个进行比较:
设置重复点数duplicate,相同斜率点数count。内部循环每次结束后更新count——和点i相同斜率的点的最大数目。(点i可能有很多相同斜率点的集合,故内层遍历完之后取最大的集合的大小。)
外部循环每次更新res为之前结果和本次循环所得duplicate+count的较大值。
重点一:以一个点为参照求其他点连线的斜率,不需要计算斜率。
重点二:两次循环体现重点一中的相对关系,可以让j从i开始,节省时间。

Solution

public class Solution {
    public int maxPoints(Point[] points) {
        // Write your code here
        int res = 0;
        if (points == null || points.length == 0) {
            return 0;
        }
        for (int i = 0; i < points.length; i++) {
            int count = 0;
            int duplicate = 1;
            Map<Double, Integer> map = new HashMap<Double, Integer>();
            Point p = points[i];
            for (int j = i; j < points.length; j++) {
                Point q = points[j];
                if (q == p) continue;
                if (q.x == p.x && q.y == p.y) duplicate++;
                else {
                    double s = p.x == q.x ? Double.MAX_VALUE: (double)(p.y-q.y)/(p.x-q.x);
                    map.put(s, map.containsKey(s) ? map.get(s)+1: 1);
                    count = Math.max(count, map.get(s));
                }
            }
            res = Math.max(res, count+duplicate);
        }
        return res;
    }
}