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

    思路:这道题主要是找出重叠结点和相同斜率之和。此时我们要判断有斜率和无斜率个数,并判断那个数量比较大,更新斜率最大值。然后在与相同情况下重叠结点个数累加。最后就是更新同一条直线上点数最大值。

    /**
     * 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.size() <= 2){
                return points.size();
            }
            
            map<double,int> slop_lines;
            int maxNumber = 0, same_points, none_slop;
            double slop;
            for(int i = 0; i < points.size()-1; ++i){
                slop_lines.clear();
                same_points = 1;
                none_slop = 0;
                for(int j = i+1; j < points.size(); ++j){
                    if(points[i].x == points[j].x &&  points[i].y == points[j].y)
                    {
                        ++same_points;
                        continue;
                    }
                    if(points[i].x == points[j].x){
                        ++none_slop;
                    }else{
                        slop = (double)(points[i].y - points[j].y)/(points[i].x - points[j].x);
                        if(slop_lines.find(slop) != slop_lines.end()){
                            ++slop_lines[slop];
                        }else{
                            slop_lines[slop] = 1;
                        }
                    }
                }
                
                //更新最大值
                map<double,int>::iterator iter = slop_lines.begin();
                for(;iter != slop_lines.end(); ++iter){
                    if(iter->second > none_slop){
                        none_slop = iter->second;
                    }
                }
                none_slop += same_points;
                if(none_slop > maxNumber){
                    maxNumber=none_slop;
                }
            }
            
            return maxNumber;
        }
    };
  • 相关阅读:
    Android_存储访问框架SAF
    Android_基础之分辨率
    Android_存储之SharedPreferences
    Android_存储之DataBase之Room
    Android_AndroidX简介&Junit4
    Android_四大组件之ContentProvider
    Android_四大组件之BroadcastReceiver
    Android_四大组件之Service
    Android启动过程_大致流程
    福利来袭,赶紧上车!
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3568515.html
Copyright © 2020-2023  润新知