leetcode.149. Max Points on a Line

来源:互联网 发布:linux卸载时出现错误 编辑:程序博客网 时间:2024/04/19 23:26

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

点和方向确定一条直线。

需要两重循环,第一重循环遍历起始点a,第二重循环遍历剩余点b。

a和b如果不重合,就可以确定一条直线。

对于每个点a,构建 斜率->点数 的map。

(1)b与a重合,以a起始的所有直线点数+1 (用dup统一相加)

(2)b与a不重合,a与b确定的直线点数+1

/** * Definition for a point. * struct Point { *     int x; *     int y; *     Point() : x(0), y(0) {} *     Point(int a, int b) : x(a), y(b) {} * }; */class Solution {public:    int maxPoints(vector<Point>& points) {        if(points.empty())            return 0;        else if(points.size() == 1)            return 1;                    int ret = 0;        for(int i = 0; i < points.size(); i ++)        {//start point            int curmax = 1; //points[i] itself            unordered_map<double, int> kcnt;    // slope_k count            int vcnt = 0;   // vertical count            int dup = 0;    // duplicate added to curmax            for(int j = 0; j < points.size(); j ++)            {                if(j != i)                {                    double deltax = points[i].x - points[j].x;                    double deltay = points[i].y - points[j].y;                    if(deltax == 0 && deltay == 0)                        dup ++;                    else if(deltax == 0)                    {                        if(vcnt == 0)                            vcnt = 2;                        else                            vcnt ++;                        curmax = max(curmax, vcnt);                    }                    else                    {                        double k = deltay / deltax;                        if(kcnt[k] == 0)                            kcnt[k] = 2;                        else                            kcnt[k] ++;                        curmax = max(curmax, kcnt[k]);                    }                }            }            ret = max(ret, curmax + dup);        }        return ret;    }};

0 0
原创粉丝点击