标签:
题目如下:
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) { int answer = 0; for(int i = 0; i < points.size(); i++){ int samePoint = 1; unordered_map<double, int> map; for(int j = i + 1; j < points.size(); j++){ if(points[i].x == points[j].x && points[i].y == points[j].y){ samePoint++; } else if(points[i].x == points[j].x){ map[INT_MAX]++; } else{ double slope = double(points[i].y - points[j].y) / double(points[i].x - points[j].x); map[slope]++; } } int localMax = 0; for(unordered_map<double, int>::iterator it = map.begin(); it != map.end(); it++){ localMax = max(localMax, it->second); } localMax += samePoint; answer = max(result, localMax); } return answer; } };
话说有没有更快的算法?
标签:
原文地址:http://www.cnblogs.com/asawanggaa/p/4435918.html