Max Points on a Line

[复制链接]
778|3
 楼主| characteristic 发表于 2019-9-15 19:59 | 显示全部楼层 |阅读模式
  • 题目链接:http://oj.leetcode.com/problems/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.
  • 题目大意:给定n个二维平面上的点,求出这n个点当中最多有多少个点在同一直线上。
  • 解题思路:每次取定一个点p1,然后求出p1与其他的n-1个点的斜率,并统计斜率相同的数目,取最大值即可。

 楼主| characteristic 发表于 2019-9-15 20:00 | 显示全部楼层
具体实现:

  1. #include <iostream>
  2. #include <map>
  3. #include <climits>

  4. using namespace std;

  5. struct Point {
  6.       int x;
  7.       int y;
  8.       Point() : x(0), y(0) {}
  9.       Point(int a, int b) : x(a), y(b) {}
  10. };

  11. class Solution {
  12. public:
  13.     int maxPoints(vector<Point> &points) {
  14.         int maxNum =0;
  15.         int size = points.size();
  16.         int i,j;
  17.         if(size <=2)   //如果点的个数小于3个,则最大数目为点的个数
  18.             return size;
  19.         for(i=0;i<size;i++)
  20.         {
  21.             int cnt =0;
  22.             map<double,int> mp;
  23.             for(j=0;j<size;j++)
  24.             {
  25.                 if(i==j)
  26.                     continue;
  27.                 if(points[i].x == points[j].x && points[i].y == points[j].y)
  28.                 {
  29.                     cnt++;
  30.                     continue;
  31.                 }  
  32.                 //注意当直线与y轴平行的情况
  33.                 double slope = points[i].x == points[j].x ? INT_MAX : (double)(points[j].y - points[i].y)/(points[j].x - points[i].x);
  34.                 mp[slope]++;
  35.             }
  36.             
  37.             if(mp.size()==0)   //防止mp为空时,下面的for循环不执行
  38.                 mp[INT_MIN] =0;
  39.             map<double,int>::iterator it = mp.begin();
  40.             for(;it!=mp.end();it++)
  41.             {
  42.                 if(it->second+ cnt > maxNum)
  43.                     maxNum = it->second +cnt;
  44.             }
  45.         }
  46.         return maxNum+1;
  47.     }
  48. };


  49. int main(int argc, char *argv[])
  50. {
  51.     vector<Point> points;
  52.     Point point[3];
  53.     int i=0;
  54.     for(i=0;i<3;i++)
  55.     {
  56.         point[i].x = 1;
  57.         point[i].y= 1;
  58.         points.push_back(point[i]);
  59.     }
  60.     Solution solution;
  61.     cout<<solution.maxPoints(points);
  62.     return 0;
  63. }
 楼主| characteristic 发表于 2019-9-15 20:00 | 显示全部楼层
这里要注意3个地方:

  1)如果点的个数小于3个,则最大数目为点的个数;

  2)考虑重复点的情况,重复点是无法计算斜率的;

  3)考虑直线与y轴平行时,斜率为无穷大的情况。
 楼主| characteristic 发表于 2019-9-15 20:00 | 显示全部楼层
作者:Matrix海子
    
出处:http://www.cnblogs.com/dolphin0520/
    
本博客中未标明转载的**归作者Matrix海子和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在**页面明显位置给出原文连接,否则保留追究法律责任的权利。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

18

主题

367

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部