您的位置:首页 > 编程语言 > C语言/C++

[LeetCode]Max Points on a Line

2014-05-16 14:29 411 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.

本题关键是找到在同一条线的点的寻找,这里寻找的原则就是,如果两个点都与一个点所得出的斜率相等,那么这两个点在同一条直线上。

开始的思路是遍历所有直线的可能,然后遍历所有的点检查是否在直线上,显然复杂度太高了。

参考:http://blog.csdn.net/doc_sgl/article/details/17103427

这里面需要考虑一些特殊情况,斜率无穷大的情况:

开始我的思路是判断如果出现x1-x2 == 0,那么就求斜率倒数,后来发现参考文章中所提出的直接判断这种的情况的key为INT_MAX的方法更加方便简介。

参考文章用的是:unordered_map,我直接用map,这方面不太懂区别,有待学习。

#include <iostream>
#include <string>
#include <vector>
#include <map>

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 duplex = 1, max = 0;
float k;
map<float, int> mp;
map<float, int>::iterator mit;
vector<Point>::iterator it1 = points.begin();
vector<Point>::iterator it2 = points.begin() + 1;
for (it1 = points.begin(); it1 != points.end(); it1++)
{
mp.clear();
mp[INT_MAX] = 0;
duplex = 1;
for (it2 = points.begin(); it2 != points.end(); it2++)
{
if (it1 == it2)
continue;
if (it1->x == it2->x && it1->y == it2->y)
{
duplex++;
continue;
}
if (it1->x == it2->x)
{
mp[INT_MAX]++;
}
else
{
k = (float)(it1->y - it2->y) / (it1->x - it2->x);
mp[k]++;
}
}
for (mit = mp.begin(); mit != mp.end(); mit++)
{
if ((mit->second + duplex) > max)
max = mit->second + duplex;
}
}
return max;
}
};

int main()
{
Solution aa;
vector<Point> pp = { Point(1, 1), Point(2, 2), Point(3, 3), Point(4, 4) };
cout << aa.maxPoints(pp) << endl;

system("PAUSE");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode