Max Points on a Line

数学题,以任意一点为中心,算其他所有点跟该点得斜率,斜率相同则在同一条直线上,用hashmap记下同一直线上的数字。
要注意corner case,坐标完全相同的点,以及横坐标相同的点(相当于斜率为无穷)。
遍历以每一个点为中心,更新最大值,即可得结果。

public class Solution {
public int maxPoints(Point[] points) {
if(points == null || points.length == 0) return 0;
int max = 1;
for(int i = 0; i < points.length; i++) {
HashMap<Float, Integer> map = new HashMap<Float, Integer>();
int same = 0, local = 0, sameX = 1;
for(int j = 0; j < points.length; j++) {
if(i == j) continue;
if(points[i].x == points[j].x) {
if(points[i].y == points[j].y){
same++;
} else {
sameX++;
}
continue;

}
float slope = (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);
if(map.containsKey(slope)) {
map.put(slope, map.get(slope) + 1);
} else {
map.put(slope, 2);
}

}
for(int count : map.values()) {
local = Math.max(local, count);
}
local = Math.max(local, sameX);
local += same;
max = Math.max(max, local);
}
return max;
}
}


posted @ 2014-12-30 09:40  江南第一少  阅读(119)  评论(0)    收藏  举报