打印

Max Points on a Line

[复制链接]
490|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 | 只看该作者
具体实现:

#include <iostream>
#include <map>
#include <climits>

using namespace std;

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) {
        int maxNum =0;
        int size = points.size();
        int i,j;
        if(size <=2)   //如果点的个数小于3个,则最大数目为点的个数
            return size;
        for(i=0;i<size;i++)
        {
            int cnt =0;
            map<double,int> mp;
            for(j=0;j<size;j++)
            {
                if(i==j)
                    continue;
                if(points[i].x == points[j].x && points[i].y == points[j].y)
                {
                    cnt++;
                    continue;
                }  
                //注意当直线与y轴平行的情况
                double slope = points[i].x == points[j].x ? INT_MAX : (double)(points[j].y - points[i].y)/(points[j].x - points[i].x);
                mp[slope]++;
            }
            
            if(mp.size()==0)   //防止mp为空时,下面的for循环不执行
                mp[INT_MIN] =0;
            map<double,int>::iterator it = mp.begin();
            for(;it!=mp.end();it++)
            {
                if(it->second+ cnt > maxNum)
                    maxNum = it->second +cnt;
            }
        }
        return maxNum+1;
    }
};


int main(int argc, char *argv[])
{
    vector<Point> points;
    Point point[3];
    int i=0;
    for(i=0;i<3;i++)
    {
        point[i].x = 1;
        point[i].y= 1;
        points.push_back(point[i]);
    }
    Solution solution;
    cout<<solution.maxPoints(points);
    return 0;
}

使用特权

评论回复
板凳
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

粉丝