Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:对于某一点来说,在经过该点的直线中选取节点数量最多的直线;对于全局来说,必定是某个局部点满足条件的直线之一=>局部最优解也是全局最优解=>贪心法。
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) { float k; int counter = 0,ret = 0,tmpMax = 0; unordered_map< float,int > slopes; for(int i = 0; i < points.size(); i++){//按点遍历,那么计算斜率就能确定一条直线,因为已有一个点的信息, for(int j = 0; j < points.size(); j++){ if(points[j].x==points[i].x&&points[j].y==points[i].y){//重合的点 counter++; continue; } k = (float)(points[j].y-points[i].y)/(points[j].x-points[i].x); slopes[k]++; } for(unordered_map< float,int >::iterator it=slopes.begin(); it!=slopes.end();it++){ tmpMax =max(tmpMax, it->second); } ret = max(tmpMax+counter, ret); counter = 0; tmpMax = 0; slopes.clear(); } return ret; } };
时间: 2024-10-10 10:13:00