题目内容
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
简明易懂
解题思路
基本方法
暴力枚举所有的直线(考虑垂直问题和重合问题特判一下)
然后将所有的斜率和截距和点数算出来直接就能给出答案
如果根本不考虑任何的优化的话,复杂度O(n^3)
而且莫名的这样都能过,看来LeetCode根本就没想卡时间
改进
注意到直线被截距和斜率唯一的标定了
于是可以为直线建立一个存储结构
算出直线后不遍历所有点得到max_point
而是搜索对应直线,将其经过点数++
注意一些特判就可以
然后这个问题的复杂度就和该结构的插入和查找相关了
如果使用了平衡树的话
复杂度应该是O(logn * n^2)
如果使用一个hash_map
复杂度就完全可以是O(n^2)
//然而标准C++的unordered_map不支持对<double, double>的hash
//真是烦人
//因此下面的代码和我的最初思路不一致一样,不要在意
class Solution { public: int maxPoints(vector<Point>& points) { int res = 0; if(points.size() <= 2) { return points.size(); } for (int i = 0; i < points.size(); i++) { unordered_map<double, int> lineThisTime; int vertical_line = 1; int same_point = 1; for (int j = i + 1; j < points.size(); j++) { if (points[i].x == points[j].x) { vertical_line++; if (points[i].y == points[j].y) { same_point++; } continue; } double k = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x); lineThisTime[k] += 1; } res = res < vertical_line ? vertical_line : res; for (unordered_map<double, int>::iterator it = lineThisTime.begin(); it != lineThisTime.end(); it++) { res = res < it->second + same_point ? it->second + same_point: res; } } return res; } };