[LintCode] Max Points on a Line

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值