题目大意:二维平面上有n个点,求共线的最大点数
下面的算法定义了一个分数类来保存斜率,其中 分子分母同时为0的时候表示无穷的情况,分子为0,分母为1 表示斜率为0的情况
基本算法为 枚举+map操作
#include <vector>
#include <iostream>
#include <map>
using namespace std;
//自定义的分数 a表示分数 b表示分母
class Key
{
public:
int a, b;
Key(): a(0), b(0){}
Key(int x, int y) : a(x), b(y){}
friend bool operator < (const Key &k1, const Key &k2)
{
if(k1.a == k2.a)
return k1.b < k2.b;
return k1.a < k2.a;
}
};
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 n = points.size();
map<Key, int> kmap;
int d = 1;
int num = 0;
for(int i = 0 ; i < n ; i++)
{
kmap.clear();
Key k;
kmap[k] = 0;
d = 1;
for(int j = 0 ; j < n; j++)
{
if(i == j) continue;
if(points[i].x == points[j].x )
{
if(points[i].y == points[j].y)
d++;
else
{
k.a = 0;
k.b = 0;
kmap[k]++;
}
}
else
{
int b = points[i].x - points[j].x;
int a = points[i].y - points[j].y;
int gab = gcd(a, b);
k.a = a / gab;
k.b = b / gab;
kmap[k]++;
}
}
for(map<Key, int>::iterator it = kmap.begin(); it != kmap.end(); it++)
if(num < it->second + d)
num = it->second + d;
}
return num;
}
int gcd(int a, int b)
{
if(b == 0)
return a;
return gcd(b, a % b);
}
};