Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题意:给出平面上若干点的(x,y)坐标,求一条直线,在这条直线上的点最多,返回这个最大点数
分析:感觉这道题的是算法和细节都有些难度的题,通过率只有10%。
算法:
O(n^2)方法:先统计每个重复点的个数,复杂度最大也就是O(n*logn),然后,对每个点,计算它与其他点的斜率,用map<斜率,个数>统计一条直线上的点数。
只要斜率的key选取得当,保证能在O(1)找到相同斜率的key,整体复杂度就是O(n^2)
细节:
1、注意空集和单点,空集返回0,单点返回1
2、这里的map的key为斜率,但由于double的精度问题不能做key,所以将斜率*10^6再取整,用long long存储,作为key
3、unodered_map不支持key为pair,即unordered_map<pair<int,int>,int>非法
4、访问pair元素方法:pair<int,int> pr,访问用pr.first,pr.second
代码:
/**
* Definition for a point.
* 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) {
if(points.empty()) return 0;
map<pair<int,int>,int> cnt;
for(int i=0; i<points.size(); i++)
{
pair<int,int> pr(points[i].x,points[i].y);
if(cnt.find(pr)==cnt.end()) cnt[pr] = 1;
else cnt[pr]++;
}
unordered_map<long long,int> mp;
int ans = 1;
for(auto p=cnt.begin(); p!=cnt.end(); p++)
{
int x = p->first.first;
int y = p->first.second;
int v = p->second;
if(v>ans) ans = v;
mp.clear();
for(auto q=cnt.begin(); q!=cnt.end(); q++)
{
if(p==q) continue;
int nx = q->first.first;
int ny = q->first.second;
int nv = q->second;
long long key;
if(x==nx) key = INT_MAX;
else key = (long long)(y-ny)*1000000/(x-nx);
if(mp.find(key)==mp.end()) mp[key] = v+nv;
else mp[key] += nv;
if(mp[key]>ans) ans = mp[key];
}
}
return ans;
}
};