• 解题报告(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.

    解题思路:题目说的非常清楚,寻找二维点在一条直线上的最大数目。

    思路一:

      首先想到的方式就是直接法,遍历每个节点,一个节点下,遍历一遍,确定一条直线后,再遍历一遍确定这条直线上的次数,这样的话,时间复杂度就是O(n3)。感觉在OJ上会跪,就不写了//不过看到刘斌的博客,貌似是可以AC的

    思路二:

      既然直接法太复杂的话,我们接着思考其他方法。我想到可以用直线的斜率k描述一条直线,把所有的点的直线搭配的斜率计算出来,存储起来,最后找到斜率出现最多的次数,就对应点最多的直线。

      考虑使用map,建立斜率k和出现次数的映射,最后取出最大的次数即可。其中需要处理,两个点相等以及斜率不存在(即横坐标相等的情况)

    代码:

     1 class Solution {
     2 public:
     3     int maxPoints(vector<Point>& points) {
     4         map<double,int> slope;           //建立斜率与出现次数的映射
     5         if(points.size() <= 2)          //点的个数小于3时,直接返回点的个数
     6             return points.size();
     7          int n = points.size(),ans = 0;     //ans为最终结果
     8         for(int i = 0; i < n - 1; i++)      
     9         {
    10             int maxNum = 0;                //记录当前节点对应的斜率出现最多的次数
    11             int same_x = 1;                //记录斜率不存在,即横坐标相等的情况
    12             int samePoint = 0;             //记录重合的点
    13             slope.clear();                
    14             for(int j = i + 1; j < n; j++)   
    15             {
    16                 
    17                   if (i == j)
    18                       continue;    
    19                   if (points[i].x == points[j].x && points[i].y == points[j].y) 
    20                   {
    21                     samePoint++;
    22                     continue;
    23                 }
    24                   if (points[i].x == points[j].x)  //斜率不存在   
    25                   {
    26                       same_x++;
    27                       continue;
    28                   }
    29                   double k = (double)(points[i].y-points[j].y)/(points[i].x-points[j].x);
    30                   if (slope.find(k) != slope.end())   //更新当前斜率出现的次数
    31                       slope[k]++;
    32                   else
    33                       slope[k] = 2;
    34             }
    35             for (map<double,int>::iterator it = slope.begin(); it != slope.end(); ++it)   //找出最大次数的斜率
    36                 same_x = max(same_x,it->second);
    37             maxNum = same_x + samePoint;
    38             ans = max(ans,maxNum);                  //与之前的最大值比较
    39         }         
    40         return ans;
    41     }
    42 };
    View Code

    在leetcode上提交,可以AC,分析一下这个算法的复杂度,外层为两个循环,内层使用map求出最大值。时间复杂度为O(n2)。

    此博客中的内容均为原创或来自网络,不用做任何商业用途。欢迎与我交流学习,我的邮箱:lsa0924@163.com

  • 相关阅读:
    使用nltk库查找英文同义词和反义词
    argostranslate 翻译的使用
    python从git上安装相应的依赖库
    json.dumps()函数解析
    python将xml文件转为json
    python匹配字符串中,某个词的位置
    TypeError: Cannot read property 'version' of undefined
    js常用工程类函数 | 下载链接 | 自定义下载内容
    C# Visual Studio 2019 代码自动补全 TAB+TAB
    国内开源镜像站点汇总
  • 原文地址:https://www.cnblogs.com/Jueis-lishuang/p/5040250.html
Copyright © 2020-2023  润新知