LeetCode Max Points on a Line

来源:互联网 发布:通达信的行情软件 编辑:程序博客网 时间:2024/06/12 23:58

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

题意:平面上给出n个点,求在同一条直线上的最多点。

思路:主要是用斜率。但是注意,水平和竖直方面上的。水平方向的斜率为0,但是浮点计算时,会出现0.0 和-0.0的问题,所以在计算水平方向时,判断y是否相等。

代码如下:

class Point {    int x;    int y;    Point() { x = 0; y = 0; }    Point(int a, int b) { x = a; y = b; }}class Solution{    public int maxPoints(Point[] points)    {        int result = 0;        Map<Double, Integer> hm = new HashMap<Double, Integer>();        for (int i = 0; i < points.length; i++)        {            int samepoint = 1;            int samex = 0;            int samey = 0;            for (int j = i + 1; j < points.length; j++)            {                if (points[i].x == points[j].x && points[i].y == points[j].y)                {                    samepoint++;                }                else if (points[i].x == points[j].x)                {                    samex++;                }                else if (points[j].y == points[i].y)                {                    samey++;                }                else                {                    double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);                    if (hm.containsKey(k))                    {                        hm.put(k, hm.get(k) + 1);                    }                    else                    {                        hm.put(k, 1);                    }                }            }            result = Integer.max(result, samepoint + samex);            result = Integer.max(result, samepoint + samey);            for (Double d : hm.keySet())            {                result = Integer.max(result, samepoint + hm.get(d));            }            hm.clear();        }        return result;    }}


0 0
原创粉丝点击