[leetcode] 149. Max Points on a Line 解题报告

来源:互联网 发布:unity3d 旧版本收费吗 编辑:程序博客网 时间:2024/06/02 06:14

题目链接:https://leetcode.com/problems/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.


思路:又是一个折磨人的题,蛋疼呐!自己写了好久,就是在hash表中以斜率和截距一对为key然后将各点保存起来,谁知道float类型的key对判等有问题。折磨了好久!

后来还是看了别人的思路,要比我的好多了。

代码如下:

/** * 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) {        int Max = 0, len = points.size();        for(int i =0; i < len; i++)        {            unordered_map<float, int> hash;            int same =1, vertical =0, curMax=0;            for(int j =i+1; j < len; j++)            {                int x1=points[i].x, y1=points[i].y, x2=points[j].x, y2=points[j].y;                if(x1 == x2 && y1 == y2) same++;                else if(x1 == x2) vertical++;                else curMax = max(curMax, ++hash[(y1-y2)/(1.0*(x1-x2))]);            }            Max = max(Max, max(curMax, vertical) + same);        }        return Max;    }};


参考:https://leetcode.com/discuss/101876/16ms-c-easy-understanding-solution


0 0
原创粉丝点击