Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Iterate over each point, calculate the slope of this point and each other point, and use a hashmap to store the slope and the number of points on that line. Note the case when there are duplicate points, and when the line is vertical. Need to add 0.0 when calculating slope to solve - 0.0 != 0.0 problem.
/**
* 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) {
if (points == null || points.length == 0) {
return 0;
}
HashMap<Double, Integer> map = new HashMap<Double, Integer>();
int max = 1;
for (int i = 0; i < points.length; i++) {
map.clear();
int dup = 0;
for (int j = i + 1; j < points.length; j++) {
if ((points[i].x == points[j].x) && (points[i].y == points[j].y)) {
dup++;
continue;
}
double k;
if (points[i].x - points[j].x == 0) {
k = Integer.MAX_VALUE;
} else {
k = 0.0 + (double) (points[i].y - points[j].y) / (double) (points[i].x - points[j].x);
}
if (map.containsKey(k) || points[i] == points[j]) {
map.put(k, map.get(k) + 1);
} else {
map.put(k, 2);
}
}
int count = 1;
for (int num : map.values()) {
count = count > num ? count : num;
}
count += dup;
max = max > count ? max : count;
}
return max;
}
}
本文介绍了一种算法,用于解决二维平面上给定点集中,找出共线点的最大数量的问题。该算法通过迭代每一点,计算它与其他各点之间的斜率,并使用哈希映射来记录每一斜率对应的点数。特别注意重复点和垂直线的情况。
545

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



