您的位置:首页 > 其它

LeetCode刷题笔录Max Points on a Line

2014-11-07 04:45 357 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.

两个点是必然共线的。三个点共线的条件是任意两点间的斜率相等。那么解法来了:对于每一个点遍历剩下的所有点并计算斜率,用一个hashmap来记录同一个slope出现的次数,这些点就是共线的点。

注意两点:

1.给的点集中可能有重复的点,两个重复的点与任何斜率都共线,因此要单独考虑identical points的情况

2.斜率可以是正无穷

/**
* 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) {
Map<Float, Integer> slopeMap = new HashMap<Float, Integer>();
if(points == null || points.length == 0)
return 0;
int max = 0;
for(int i = 0; i < points.length; i++){
slopeMap.clear();
//to store potential identical duplicate points
int identicals = 1;
for(int j = 0; j < points.length; j++){
if(i == j)
continue;
int x1 = points[i].x;
int y1 = points[i].y;
int x2 = points[j].x;
int y2 = points[j].y;

//if the two points are identical
if(x1 == x2 && y1 == y2){
identicals++;
continue;
}
Float slope = (x2 - x1 == 0) ? Float.MAX_VALUE : ((float)(y2 - y1) / (x2 - x1));
if(slopeMap.containsKey(slope)){
int prevCount = slopeMap.get(slope);
slopeMap.put(slope, prevCount + 1);
}
else
slopeMap.put(slope, 1);
}
if(slopeMap.isEmpty()){
max = Math.max(max, identicals);
}
for(Map.Entry<Float, Integer> entry : slopeMap.entrySet()){
max = Math.max(max, entry.getValue() + identicals);
}
}

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