您的位置:首页 > 其它

LeetCode | Max Points on a Line

2013-12-11 13:31 453 查看



题目:

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:
    int maxPoints(vector<Point> &points) {
        if(points.size() <= 2){
            return points.size();
        }
        
        int max = 2;
        int cur = 1;
        for(int i = 0; i < points.size(); i++){
            int duplicate = 0;
            for(int j = i + 1; j < points.size(); j++){
                if(points[i].x == points[j].x && points[i].y == points[j].y){
                    duplicate++;
                    continue;
                }
                cur++;
                
                for(int k = j + 1; k < points.size(); k++){
                    if(sameLine(points[i], points[j], points[k])){
                        cur++;
                    }
                }
                
                if(cur + duplicate > max){
                    max = cur + duplicate;
                }
                cur = 1;
            }
            
            if(cur + duplicate > max){
                max = cur;
            }
            cur = 1;
        }
        
        return max;
    }
    
    bool sameLine(Point p1, Point p2, Point p3){
        return (p2.y - p3.y) * (p1.x - p3.x) == (p1.y - p3.y) * (p2.x - p3.x);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: