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

149 Max Points on a Line 直线上最多的点数

时间:2018-04-06 15:24:40      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:for   public   pos   second   turn   bsp   etc   map   tor   

给定二维平面上有 n 个点,求最多有多少点在同一条直线上。

详见:https://leetcode.com/problems/max-points-on-a-line/description/

    /** 
     * 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) {
        int res = 0;
        for (int i = 0; i < points.size(); ++i)
        {
            map<pair<int, int>, int> m;
            int duplicate = 1;
            for (int j = i + 1; j < points.size(); ++j) 
            {
                if (points[i].x == points[j].x && points[i].y == points[j].y) 
                {
                    ++duplicate;
                    continue;
                } 
                int dx = points[j].x - points[i].x;
                int dy = points[j].y - points[i].y;
                int d = gcd(dx, dy);
                ++m[{dx / d, dy / d}];
            }
            res = max(res, duplicate);
            for (auto it = m.begin(); it != m.end(); ++it)
            {
                res = max(res, it->second + duplicate);
            }
        }
        return res;
    }
    int gcd(int a, int b)
    {
        return (b == 0) ? a : gcd(b, a % b);
    }
};

 参考:https://www.cnblogs.com/grandyang/p/4579693.html

149 Max Points on a Line 直线上最多的点数

标签:for   public   pos   second   turn   bsp   etc   map   tor   

原文地址:https://www.cnblogs.com/xidian2014/p/8727564.html

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