• 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.


    思路:hash表

    首先一个方法就是hash内容是斜率和个数

    从前往后判断,计算每一个点的斜率,当然需要首先判断是否垂直点,是否同一个点,然后再hash[slope],随时输出最大值,这个只是代表了非同一个点。

    还需要加上相同点。接下来还需要和垂直点个数比较。


    代码:

    /**
     * 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;
            
            int n=points.size();
            int result=0;
            
            for(int i=0;i<n;i++){
                unordered_map<double,int> counter;
                int same=1;
                int ver=1;
                int maxCount=0;
                
                for(int j=i+1;j<n;j++){
                    if(points[i].x==points[j].x&&points[i].y==points[j].y){
                        //这个时候是同一个点
                        same++;
                        ver++;
                    }else if(points[i].x==points[j].x){
                        ver++;
                    }else{
                        double slope=1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);
                        //这个地方不写1.0*....就是错误啊
                        ++counter[slope];
                        if(counter[slope]>maxCount)   maxCount=counter[slope];
                    }
                }
                maxCount+=same;
                if(maxCount<ver)    maxCount=ver;
                if(maxCount>result) result=maxCount;
            }
            
            return result;
        }
    };


  • 相关阅读:
    multipath路径残留导致虚拟机无法重启
    multipath配置错误导致的云平台虚拟机挂载云硬盘失败
    kubernetes v1.8.3安装coredns
    helm安装chart----percona-xtradb-cluster实践记录
    elasticsearch性能调优相关
    nova hypervisor-list无法执行,其他api均正常
    珍爱面经
    猫眼面经
    头条面经
    阿里秋招面经
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519866.html
Copyright © 2020-2023  润新知