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;
}
}

本文详细介绍了如何通过遍历每个点并计算与其他点之间的斜率来找出二维平面上最多共线点数的方法。讨论了处理重复点及斜率为正无穷的情况,并提供了关键代码实现细节。

被折叠的 条评论
为什么被折叠?



