您的位置:首页 > 其它

【leetcode】Max Points on a Line

2014-04-29 20:23 447 查看
题目:Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.

解法:从任意一点开始,找斜率相同的最大点数,用HashMap

代码:

/**
* 从任意一点开始,找斜率相同的最大点数
* 特别注意和开始点重点的情况
* @param points
* @return
*/
public int maxPoints(Point[] points){
HashMap<Float, Integer> slopeMap = new HashMap<Float, Integer>();
int size = points.length;
if(size == 0 || size == 1)
return size;
int maxSlopeTime = 1;
for(int i = 0; i < size; i++){
slopeMap.clear();
int tempMaxSlopeTime = 0;;
int duplicate = 1;//表示和第i个点重复的次数
for(int j = i + 1; j < size; j++){
if(points[i].x == points[j].x && points[i].y == points[j].y){
duplicate++;
continue;
}
float dx = points[i].x - points[j].x;
float dy = points[i].y - points[j].y;
float slope;
if(dx == 0.0f)
slope = 0.0f;//如果直接用dy/dx,则会有-0.0和0.0两种情况
else if(dy == 0.0f)
slope = Float.POSITIVE_INFINITY;//如果直接用dy/dx,则会有-infinity和infinity两种情况
else
slope = dy/dx;
if(slopeMap.containsKey(slope)){
slopeMap.put(slope, slopeMap.get(slope) + 1);
if(tempMaxSlopeTime < slopeMap.get(slope))
tempMaxSlopeTime = slopeMap.get(slope);
}
else{
slopeMap.put(slope, 1);
if(tempMaxSlopeTime < 1)
tempMaxSlopeTime = 1;
}
}
if(tempMaxSlopeTime + duplicate > maxSlopeTime)
maxSlopeTime = tempMaxSlopeTime + duplicate;
}
return maxSlopeTime;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: