zoukankan      html  css  js  c++  java
  • LeetCode: 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.

    Solution:

    /**
     * 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) {
            //key is slope, value is the number of points in the line of a given slope
            //this map will be reused
            if (points.size() <= 1){
                return points.size();
            }
            unordered_map<double, int> slopeMap;
            int result = 0;
            for (unsigned i = 0; i < points.size(); i++){
                slopeMap.clear();
     
                Point anchorPoint = points[i];
                int dupPointCount = 0;
                int dupLineCount = 1;
                for (unsigned j = i + 1; j < points.size(); j++){
                    Point currentPoint = points[j];
                    //same point should be count in every line
                    if (anchorPoint.x == currentPoint.x && anchorPoint.y == currentPoint.y){
                        dupPointCount++;
                    } else {//not same point
                        double slope = std::numeric_limits<double>::infinity();
                        if (anchorPoint.x != currentPoint.x){//avoid divide 0 error
                            slope = (double)(anchorPoint.y - currentPoint.y) / (anchorPoint.x - currentPoint.x);
                        }
                        if (slopeMap.find(slope) == slopeMap.end()){//slope first appear
                            slopeMap[slope] = 1;
                        }
                        slopeMap[slope]++;
                        int currentLinePointCount = slopeMap[slope];
                        if (currentLinePointCount > dupLineCount){
                            dupLineCount = currentLinePointCount;
                        }
                    }
                }
                if (dupLineCount + dupPointCount > result){
                    result = dupLineCount + dupPointCount;
                }
            }
            return result;
        }
    };
  • 相关阅读:
    Redis安装
    mysql 存储过程与存储函数
    mysql 常用函数
    cpu-z笔记本加条子
    centos上网络服务起不来network.service failed
    centos/redhat命令行上传下载文件
    docker删除已经停止的容器
    centos/redhat/ubuntu不同之处
    部署lamp动态网站(图解)
    写交互式脚本时,遇到到报错:not a regular file
  • 原文地址:https://www.cnblogs.com/yeek/p/3560828.html
Copyright © 2011-2022 走看看