max-points-on-a-line

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

class Point

{
    int x;
    int y;
    Point() { x = 0; y = 0; }
    Point(int a, int b) { x = a; y = b; }

}

public class MaxPointsOnALine

{
    public static int run(Point[] points)
    {
        Map<Double, Integer> _map = new HashMap<Double, Integer>();//key为斜率 value为点的数量
        int _max = 0;//记录直线上点的数量
        
        for(int i =0 ; i < points.length; ++i)
        {
            _map.clear();//每次遍历一个点时,清空hash表
            _map.put((double)Integer.MIN_VALUE, 1);
            int _dup = 0;//记录重复的点(x、y坐标相等)
            for(int j = i + 1; j < points.length; ++j)
            {
                double _y = (double)(points[j].y - points[i].y);
                double _x = (double)(points[j].x - points[i].x);
                if(_y == 0 && _x == 0)
                {
                    ++_dup;
                    continue;
                }
                //如果两个点的x坐标相同(垂直),斜率取Integer.MIN_VALUE
                double _key = points[i].x == points[j].x ? (double)Integer.MIN_VALUE : _y / _x;
                if(_map.containsKey(_key))
                {
                    _map.put(_key, _map.get(_key) + 1);
                }
                else
                {
                    _map.put(_key, 2);
                }
            }
            for(int _temp : _map.values())
            {
                if(_temp + _dup > _max)
                {
                    _max = _temp + _dup;
                }
            }
        }
        return _max;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值