//Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
class Point
{int x;
int y;
Point() { x = 0; y = 0; }
Point(int a, int b) { x = a; y = b; }
}
public class MaxPointsOnALine
{
public static int run(Point[] points)
{
Map<Double, Integer> _map = new HashMap<Double, Integer>();//key为斜率 value为点的数量
int _max = 0;//记录直线上点的数量
for(int i =0 ; i < points.length; ++i)
{
_map.clear();//每次遍历一个点时,清空hash表
_map.put((double)Integer.MIN_VALUE, 1);
int _dup = 0;//记录重复的点(x、y坐标相等)
for(int j = i + 1; j < points.length; ++j)
{
double _y = (double)(points[j].y - points[i].y);
double _x = (double)(points[j].x - points[i].x);
if(_y == 0 && _x == 0)
{
++_dup;
continue;
}
//如果两个点的x坐标相同(垂直),斜率取Integer.MIN_VALUE
double _key = points[i].x == points[j].x ? (double)Integer.MIN_VALUE : _y / _x;
if(_map.containsKey(_key))
{
_map.put(_key, _map.get(_key) + 1);
}
else
{
_map.put(_key, 2);
}
}
for(int _temp : _map.values())
{
if(_temp + _dup > _max)
{
_max = _temp + _dup;
}
}
}
return _max;
}
}