[LeetCode]149. Max Points on a Line
题目描述
思路
对每个点,将所有可能的直线存储在map中,并记录直线上对应的点,每次返回点最多的个数
踩的坑:
1. 开始考虑存直线需要 y = k * x + b, 即需存储k, b两个值,后来想想,通过同一点的直线,只需要k即可确定,相同的k值代表相同的直线
2. k值存在为无穷大的问题,即直线与y轴垂直的时候。
3. k值精度问题,如果保存的是k值,当数据过大时候k值会直接相同,因此选择保存的是类似分数的形式,对diffY和diffX求最大公约数,之后保存他们对应的最简分数,可以较为准确的区分
代码
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <cmath>
#include <algorithm>
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 GCD(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
int maxPoint(vector<Point>& points) {
if (points.size() <= 2)
return points.size();
int res = 0;
for (int i = 0; i < points.size() - 1; ++i) {
map<pair<int, int>, int> pointCount;
int vertical = 0, sameCount = 1;
for (int j = i + 1; j < points.size(); ++j) {
if (points[j].x == points[i].x && points[j].y != points[i].y)
++vertical;
else if (points[j].x == points[i].x && points[j].y == points[i].y)
++sameCount;
else {
//double k = (float)(points[j].y - points[i].y) / (float)(points[j].x - points[i].x);
//long double k = atan((long double)((long double)(points[j].y - points[i].y) / points[j].x - points[i].x));
//cout << k << endl;
int diffY = points[j].y - points[i].y, diffX = points[j].x - points[i].x;
int gcd = GCD(diffY, diffX);
diffY /= gcd, diffX /= gcd;
++pointCount[make_pair(diffX, diffY)];
}
}
res = max(res, vertical + sameCount);
for (auto &p : pointCount) {
res = max(res, p.second + sameCount);
}
}
return res;
}
};
int main() {
vector<Point> points = { Point(0, 0), Point(94911151, 94911150), Point(94911152, 94911151) };
Solution s;
cout << s.maxPoint(points) << endl;
system("pause");
}