您的位置:首页 > 其它

Problem Max Points On a Line

2014-06-29 13:47 232 查看
Problem Description:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Solution:

public int maxPoints(Point[] points) {
if (points.length <= 1) {
return points.length;
}
Map<Double, Integer> map = new HashMap<Double, Integer>();
int maxPoints = 0;
for (int i = 0; i < points.length; i++) {
map.clear();
int samePointCount = 1;
int max = 0;
for (int j = i+1; j < points.length; j++) {
if (points[i].x == points[j].x &&
points[i].y == points[j].y) {
samePointCount++;
} else {
double slope = Double.MAX_VALUE;
if (points[i].y == points[j].y) {
slope = 0;
}
else if (points[i].x != points[j].x)
slope = (points[i].y - points[j].y) / (double) (points[i].x - points[j].x);
if (! map.containsKey(slope)) {
map.put(slope, 1);
} else {
map.put(slope, map.get(slope)+1);
}

if (map.get(slope) > max) {
max = map.get(slope);
}

}
}
if (max + samePointCount  > maxPoints) {
maxPoints = max + samePointCount ;
}
}
return maxPoints;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: