前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 149 Max Points on a Line

Leetcode 149 Max Points on a Line

作者头像
triplebee
发布2018-01-12 14:50:50
7680
发布2018-01-12 14:50:50
举报

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

给一个点集,判断在一条直线上的点最多有多少个。

枚举每一个点,算其他点和它的斜率,然后用一个unordered_map记录斜率出现的次数。

注意处理好分母为0,和两点重合的情况。

也是佩服discuss中的朋友,有人想到用hough transform做,

虽然在RHO大的情况下,这种算法并不能保证完全正确,只能求出近似解,不能完全通过这题,但是这个想法很好!

我只是提一下,不要当真,好好用正解做题。

代码语言:javascript
复制
/**
 * 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) {
        unordered_map<double, int> mp;
        int res = 0;
        for(int i = 0; i < points.size(); i++)
        {
            int re = 0, temp = 0, resp = 0;
            for(int j = i+1; j < points.size(); j++)
            {
                if(points[i].x == points[j].x)
                {
                    if(points[i].y == points[j].y) 
                        re++;
                    else
                        temp++;
                }
                else
                {
                    double k = 1.0*(points[i].y - points[j].y)/(points[i].x - points[j].x);
                    mp[k]++;
                    resp = max(resp, mp[k]);
                }
            }
            res = max(res, max(resp, temp) + re + 1);
            mp.clear();
        }
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-12-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档