这篇博客已经写了很久了,当时由于解答了此题目。没有想的更多,就直接发了博客,当昨天在此提到这个题目,我竟然有些不记得了。
稍微用我自己的语言升华了一下:
由于本题目是要找共线的点的个数,那么显然,我们可能使用枚举 的方式,枚举所有的O(n^2)条直线的斜率,看哪些斜率满足共线的条件,这显然是O(n^3)的复杂度。。
如果以每一个点来说,只有两种情况,要么在最优解的直线上,要么不在,如果在,那么与该点共线的直线即为所求,这样每个节点的时间复杂度即为O(n),每个点这样考虑,即为O(n^2),因此我们使用上面的方法。
这让我想到了,“最大子数组和”,这个问题的暴力枚举的复杂度为O(n^2),但是像上面一样,我们考虑每个元素要么在,要么不在,那么就直接降到了线性的O(n).
诸如,最长公共子序列,等等情况,换个角度想,就会有意外的收获。
题目描述:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:点是否共线,从斜率入手。
注意:在提交的过程中,我发现,如果给定的n个点中有重复的点,也是当做不同的点来计算的。
例如:如果所有的n个点一样的话,那么共线的点的个数就应该是n。
如果(n-1)个点完全一样,另外一个点不一样,那么共线的点的个数也是(n-1) +1 = n个。
基于此,对于所有的点,首先应该预处理成两两互异的点。对于其中的某一个点,计算该点与其他点构成的点对之间的斜率,并统计每一个斜率下的点的个数,求出最大,即为所求得的当前点与其他点的能够构成的最多的共线的点的个数。依次下去,可以得到 与每一个点最多的共线的点个数。求出这n个值中的最大值即为所求。
代码如下:
/**
* 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) {
const int n = points.size();
if( n == 0 ) return 0;
if( n == 1 ) return 1;
map<float, int> count;
map<float, int>::iterator iter;
map<pair<int,int>, int> same;
for(int i = 0 ; i < n ; ++i)
{
pair<int,int> p1 = make_pair(points[i].x , points[i].y);
if(same.find(p1) != same.end())
++same[p1];
else
same.insert(map<pair<int,int>, int>::value_type(p1, 1));
//same[p1] = 1;
}
//only one point
if( same.size() == 1 )return (same.begin())->second;
int maxCount = 0;
for(map<pair<int,int>, int>::iterator sameIter = same.begin(); sameIter != same.end(); sameIter++)
{
count.clear(); //record the points share a line with p1
assert(count.empty());
pair<int,int> p1 = sameIter->first;
for(map<pair<int,int>, int>::iterator sameIter2 = same.begin(); sameIter2 != same.end() ; sameIter2++)
{
pair<int,int> p2 = sameIter2->first;
if(p1 == p2) continue; //ignore itself
float k = 0;
if(p1.first == p2.first)
{
k = numeric_limits<float>::max(); //the points with the same x axis,the slope is infinite
}
else
{
k = 1.0*(float)(p1.second - p2.second)/(float)(p1.first - p2.first);
}
if(count.find(k) != count.end())
count[k] += (sameIter2->second);
else
count.insert(map<float,int>::value_type(k,sameIter2->second));
}
int temp = 0;
for(map<float, int>::iterator iter = count.begin(); iter != count.end(); ++iter)
{
if(iter->second > temp)
temp = iter->second;
}
if(maxCount < (temp + sameIter->second))maxCount = temp + sameIter->second;
}
return maxCount;
}
};