Given
n
points on a 2D plane, find the maximum number of points that lie on the same straight line.、
思路:brute ways,O(N^2)时间复杂度。
如果x轴坐标一致:
1. Y轴坐标也一样的话就是同一个点,用same标记
2. Y轴坐标不一样,在一条垂直线上,用vertical标记
如果x轴坐标不一样,则可以计算斜率:
3. 以任一个点(遍历)为起点,计算其与每一个点的斜率。斜率用hash表(字典)来存储。
其中3和2值中的较大值加上1值即为结果
c++ 参考代码:
/**
* 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;
unordered_map<double, int>dm;
int ans = 0, vertical = 0, same = 0, maxdm = 0;
double dslope = 0.0;
for(int i = 0; i<points.size(); ++i)
{
dm.clear();
dslope = vertical = same = maxdm = 0;
for(int j = 0; j<points.size(); ++j)
{
if(points[i].x==points[j].x)
{
if(points[i].y==points[j].y)
++same;
else
++vertical;
}
else
{
dslope = (double)(points[j].y-points[i].y) / (points[j].x-points[i].x);
++dm[dslope];
maxdm = max(maxdm, dm[dslope]);
}
}
ans = max(ans, max(vertical, maxdm)+same);
}
return ans;
}
};
python参考代码:
# Definition for a point
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
# @param points, a list of Points
# @return an integer
def maxPoints(self, points):
if not points:return 0
ans = 0
slope = 0.0
for i in points:
dict = {}
maxdict = vertical = same = 0
for j in points:
if i.x==j.x:
if i.y==j.y:
same += 1
else:
vertical += 1
else:
slope = float(j.y-i.y) / (j.x-i.x)
if dict.has_key(slope):
dict[slope] += 1
else:
dict[slope] = 1
maxdict = max(maxdict, dict[slope])
ans = max(ans, max(maxdict, vertical)+same)
return ans
//SECOND TRIAL, almost the sameclass Solution {public :int maxPoints ( vector < Point > & points ) {if ( points . empty ())return 0 ;else if ( points . size () <= 2 )return points . size ();int same = 0 , vertical = 0 , slope_cnt = 0 , ans = 0 ;float slope ;unordered_map < float , int > mp ;for ( int i = 0 ; i < points . size (); ++ i ){same = vertical = slope_cnt = 0 ;mp . clear ();for ( int j = 0 ; j < points . size (); ++ j ){if ( j != i ){if ( points [ j ]. x == points [ i ]. x ){if ( points [ j ]. y == points [ i ]. y )++ same ;else++ vertical ;}else{slope = float ( points [ j ]. y - points [ i ]. y ) / ( points [ j ]. x - points [ i ]. x );++ mp [ slope ];if ( mp [ slope ] > slope_cnt )slope_cnt = mp [ slope ];}}}ans = max ( ans , 1 + same + max ( slope_cnt , vertical ));}return ans ;}};