Max Points on a Line

来源:互联网 发布:伪装苹果在线软件 编辑:程序博客网 时间:2024/06/03 21:20
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
#define INFINITE_SLOP999999.99struct 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.empty())return 0;int size = points.size();int maxPoints = 1;for(int i = 0; i < size ; i++){map <float, int> slopes;int numSamePoints = 0;for(int j = i ; j < size ; j++){if (points[i].x == points[j].x && points[i].y == points[j].y){numSamePoints++;continue;}float slope = (points[i].x == points[j].x ? INFINITE_SLOP : (float)(points[i].y - points[j].y) / (float)(points[i].x - points[j].x));if (slopes.find(slope) == slopes.end())slopes.insert(pair<float, int> (slope, 1));elseslopes[slope]++;}for(map<float, int>::iterator it = slopes.begin();it != slopes.end(); ++it)maxPoints = it->second + numSamePoints > maxPoints ? it->second  + numSamePoints: maxPoints;maxPoints = numSamePoints > maxPoints ? numSamePoints : maxPoints;}return maxPoints;}};

0 0