码迷,mamicode.com
首页 > 其他好文 > 详细

Max Points on a Line

时间:2014-05-30 16:27:19      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

bubuko.com,布布扣
/**
 * 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;
    }
};
bubuko.com,布布扣

 

Max Points on a Line,布布扣,bubuko.com

Max Points on a Line

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!