首页 > 代码库 > Max Points on a Line

Max Points on a Line

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:
    bool isCollineation(Point& p1, Point& p2, Point& p3) //判断三点是否共线
    {
        int x1 = p1.x - p2.x ;
        int y1 = p1.y - p2.y ;
        int x2 = p1.x - p3.x ;
        int y2 = p1.y - p3.y ;
        if (x1 * y2 - x2 * y1 == 0)
            return true ;
        return false ;
    } ;
    int maxPoints(vector<Point> &points) 
    {
        int n=points.size();
        if(n<3) return n;
        
        int max=0;
        bool flagalldup=true;
        for(int i=0;i<n-2;i++)
        {
            int dup=0;
            for(int j=i+1;j<n-1;j++)
            {
                if(points[i].x==points[j].x && points[i].y==points[j].y) 
                {
                    dup++;continue;
                }
                
                int line=2;
                for(int k=j+1;k<n;k++)
                {
                    flagalldup=false;
                    if(isCollineation(points[i],points[j],points[k]))
                        line=line+1;
                }
                line=line+dup;
                if(line>max) max=line;
            }
        }
        
        if(flagalldup) return n;
        else return max;
    }
};