max-point-on-a-line

来源:互联网 发布:python干什么厉害 编辑:程序博客网 时间:2024/04/30 03:45

题目描述

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

穷举法,遍历即可,注意判断斜率需要转成double型

/** * 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 countpoint(int x1,int y1,int x2,int y2,vector<Point> &points)        {               int res=0;               if (x1==x2&&y1!=y2)                    {                   for(auto c:points)                       {                       if(c.x==x1)                           ++res;                   }                }                else if(x1==x2&&y1==y2)                    {                    for(auto c:points)                       {                       if(c.x==x1&&c.y==y1)                           ++res;                   }                }                else if (x1!=x2&&y1==y2)                    {                    for(auto c:points)                       {                       if(c.y==y1)                           ++res;                   }                }                else                    {                    for(auto c:points)                       {                       if(abs(static_cast<double>(c.y-y2)/static_cast<double>(y1-y2)                           -static_cast<double>(c.x-x2)/static_cast<double>(x1-x2))<0.00000001)                           ++res;                   }                }            return res;    }    int maxPoints(vector<Point> &points) {        if(points.size()<=1)            return points.size();        int max=0;        for(int i=0;i!=points.size();++i)            {            for(int j=i+1;j!=points.size();++j)                {                    int temp=countpoint(points[i].x,points[i].y,points[j].x,points[j].y,points);                    if(temp>max)                        max=temp;                               }        }       return max;     }};
0 0
原创粉丝点击