您的位置:首页 > 其它

Leetcode no. 149

2016-07-26 20:59 381 查看
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.

/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
if (points.length<= 2) return points.length;
int res=0;
for (int i = 0; i < points.length; i++) {
int infinite=1, samepoint=0;
Map<Double, Integer> map= new HashMap<>();
for (int j = 0; j < points.length; j++) {
if (i==j) continue;
if ((points[i].x== points[j].x)&& (points[j].y== points[i].y)) samepoint++;
if (points[i].x== points[j].x){
infinite++;
continue;
}
double angle= ((double)(points[j].y-points[i].y))/((double)(points[j].x-points[i].x));
if (map.containsKey(angle)) map.put(angle, map.get(angle)+1);
else map.put(angle, 2);
res= Math.max(res, map.get(angle)+samepoint);
}
res= Math.max(res, infinite);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: