Max Points on a Line

来源:互联网 发布:经济学推荐书籍 知乎 编辑:程序博客网 时间:2024/06/16 03:35

------QUESTION------

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

------SOLUTION------
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;    }};


0 0