码迷,mamicode.com
首页 > 其他好文 > 详细

求一条直线通过的最大点数

时间:2015-10-21 12:04:46      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

题目: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;
    }

 

求一条直线通过的最大点数

标签:

原文地址:http://www.cnblogs.com/lasclocker/p/4897161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!