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 ;
		return (x1 * y2 == x2 * y1);
	
	} ;
    int maxPoints(vector &points) {
 
        if (points.size() <= 2) return points.size() ;
		int maxLine = 2 ;// 初始maxLine为2,因为必有两点共线
 
		bool flag = false ; //用来表示是否所有的点都重合
		for (size_t i = 0; i < points.size(); ++ i)
		{
			int cpyNum = 0 ; //重复出现的点的个数
			for (size_t j = i + 1; j < points.size(); ++ j)
			{
				if (points[i].x == points[j].x && points[i].y == points[j].y) // 计算第一个与i点不重合的点之前的与i点重合的点的个数
				{
					cpyNum ++ ;
					continue ;
				}
				flag = true ; // 点j不与i点重合
				int count = 2 + cpyNum ;// i点+必有与i点在一条直线上的另一条点+与i点重合的点的个数
				for (size_t k = j + 1; k < points.size(); ++ k)
					if (isCollineation(points[i], points[j], points[k]))
						count ++ ;
				if (count > maxLine)
					maxLine = count ;
			}
		}
 
		if (!flag) maxLine = points.size() ; // 如果所有的点都重合
		return maxLine ;
    }
};

你可能感兴趣的:(LeetCode)