zoukankan      html  css  js  c++  java
  • 【LeetCode】149. Max Points on a Line

    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.

    点和方向确定一条直线。

    需要两重循环,第一重循环遍历起始点a,第二重循环遍历剩余点b。

    a和b如果不重合,就可以确定一条直线。

    对于每个点a,构建 斜率->点数 的map。

    (1)b与a重合,以a起始的所有直线点数+1 (用dup统一相加)

    (2)b与a不重合,a与b确定的直线点数+1

    /**
     * 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.empty())
                return 0;
            else if(points.size() == 1)
                return 1;
                
            int ret = 0;
            for(int i = 0; i < points.size(); i ++)
            {//start point
                int curmax = 1; //points[i] itself
                unordered_map<double, int> kcnt;    // slope_k count
                int vcnt = 0;   // vertical count
                int dup = 0;    // duplicate added to curmax
                for(int j = 0; j < points.size(); j ++)
                {
                    if(j != i)
                    {
                        double deltax = points[i].x - points[j].x;
                        double deltay = points[i].y - points[j].y;
                        if(deltax == 0 && deltay == 0)
                            dup ++;
                        else if(deltax == 0)
                        {
                            if(vcnt == 0)
                                vcnt = 2;
                            else
                                vcnt ++;
                            curmax = max(curmax, vcnt);
                        }
                        else
                        {
                            double k = deltay / deltax;
                            if(kcnt[k] == 0)
                                kcnt[k] = 2;
                            else
                                kcnt[k] ++;
                            curmax = max(curmax, kcnt[k]);
                        }
                    }
                }
                ret = max(ret, curmax + dup);
            }
            return ret;
        }
    };

  • 相关阅读:
    AWS EC2服务器的HTTPS负载均衡器配置过程
    大数据技术Hadoop笔试题
    网上找的hadoop面试题目及答案
    360全景图three.js
    360全景图three.js与Photo-Sphere-Viewer-master 3D全景浏览开发
    @font-face 字体
    scss语法
    6.事件
    5.回调函数
    4.querystring属性
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3825063.html
Copyright © 2011-2022 走看看