Max Points on a Line [leetcode]

来源:互联网 发布:帝国cms html5模板 编辑:程序博客网 时间:2024/05/08 09:10

思路:对每个点,记录<斜率, 点的个数>对

因为一条直线可以由点+斜率决定,所以相同斜率必在同一条直线上

    int maxPoints(vector<Point> &points) {        int n = points.size();        int maxRes = 0;        for (int i = 0; i < n; i++)        {            int samePoint = 0, x0 = 0, curMax = 0;            map<double, int> kMap;            for (int j = 0; j < n; j++)            {                if (points[i].x == points[j].x && points[i].y == points[j].y)                     samePoint++;                else if (points[i].x == points[j].x)                     curMax = max(curMax, ++x0);                else                {                    double k = (points[i].y - points[j].y + 0.0) / (points[i].x - points[j].x);                    curMax = max(curMax, ++kMap[k]);                }            }            maxRes = max(curMax + samePoint, maxRes);        }        return maxRes;    }


0 0