标签:style blog color for io div
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:这道题主要是找出重叠结点和相同斜率之和。此时我们要判断有斜率和无斜率个数,并判断那个数量比较大,更新斜率最大值。然后在与相同情况下重叠结点个数累加。最后就是更新同一条直线上点数最大值。
/** * 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.size() <= 2){ return points.size(); } map<double,int> slop_lines; int maxNumber = 0, same_points, none_slop; double slop; for(int i = 0; i < points.size()-1; ++i){ slop_lines.clear(); same_points = 1; none_slop = 0; for(int j = i+1; j < points.size(); ++j){ if(points[i].x == points[j].x && points[i].y == points[j].y) { ++same_points; continue; } if(points[i].x == points[j].x){ ++none_slop; }else{ slop = (double)(points[i].y - points[j].y)/(points[i].x - points[j].x); if(slop_lines.find(slop) != slop_lines.end()){ ++slop_lines[slop]; }else{ slop_lines[slop] = 1; } } } //更新最大值 map<double,int>::iterator iter = slop_lines.begin(); for(;iter != slop_lines.end(); ++iter){ if(iter->second > none_slop){ none_slop = iter->second; } } none_slop += same_points; if(none_slop > maxNumber){ maxNumber=none_slop; } } return maxNumber; } };
Max Points on a line,布布扣,bubuko.com
标签:style blog color for io div
原文地址:http://www.cnblogs.com/awy-blog/p/3568515.html