149. 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.
Example 1:
Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
Example 2:
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
题目链接:https://leetcode.com/problems/max-points-on-a-line/
解题思路
题目思路与计算回旋镖数量那道题思路一样,关键在于查找表中储存什么。本题储存的是同一个点与其他所有各点的斜率情况统计。
时间复杂度:O(n^2)
空间复杂度:O(n)
几个写代码中的要点:
1.不要忘记垂直的线无法计算斜率。
2.相同点也计数。
3.记录精度有2种方法:
1)直接计算dy/dx:快,但有精度问题。
2)dy和dx除去最大公约数之后记录为分数的字符串:慢,但能储存任何精度。
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int res=0;
for(int i=0;i<points.size();++i){
unordered_map<string,int> record;
int strait = 0;
int same=0;
for(int j=0;j<points.size();++j){
if(i==j)continue;
if((points[i][0]==points[j][0])&&(points[i][1]==points[j][1])) same++;
else if((points[i][0]==points[j][0])&&(points[i][1]!=points[j][1])) strait++;
else{
int dy = points[i][1]-points[j][1];
int dx = points[i][0]-points[j][0];
int gcd = generateGCD(dx, dy);
dx /= gcd;
dy /= gcd;
string tmp = to_string(dy)+"/"+to_string(dx);
record[tmp]++;
}
}
for(auto iter=record.begin();iter!=record.end();++iter){
res = max(res,iter->second+same+1);
}
res = max(res, strait+same+1);
}
return res;
}
int generateGCD(int a, int b){
if (b == 0){
return a;
} else {
return generateGCD(b, a % b);
}
}
};