LeetCode 149. Max Points on a Line

来源:互联网 发布:json美化 js 编辑:程序博客网 时间:2024/03/29 16:25

参考了别人的题解


对于每个点

1. 都可以和其他的n-1个点中不和自己重叠的点连线。用map记录从该点出发,斜率(点+斜率确定直线)和在该条线上的点数的对应关系。

2. 记录使得斜率为0的(与x轴垂直)点的个数vertical

3. 记录和该点重合的点数(包括自身)increment

在map的值以及vertical中找出最大的数maxx;

 maxx+increment即为经过该点的直线能包含的最多点的个数。

遍历所有点,找出maxx+increment的最大值。


代码:

class Solution {public:int maxPoints(vector<Point> &points) {int cnt = 0;for (size_t i = 0; i < points.size(); ++ i){map<double, int> slope;int increment = 0;int vertical_line = 0;for (size_t j = 0; j < points.size(); ++ j){if (points[i].x==points[j].x && points[i].y==points[j].y) // include itself{++ increment;} else if (points[i].x==points[j].x){++ vertical_line;} else{++ slope[1.0*(points[j].y-points[i].y) / (points[j].x-points[i].x)]; // int cast to double!!}}int maxx = 0;for (auto it = slope.begin(); it != slope.end(); ++ it){maxx = maxx>it->second? maxx: it->second;}maxx = maxx>vertical_line? maxx: vertical_line;cnt = cnt>maxx+increment? cnt: maxx+increment;}return cnt;}};


0 0
原创粉丝点击