题目大意:给定一系列二维空间内的点,找出这些点中在一条直线上最多的点的个数。
分析理解:判断两个点是否在一条直线上可以根据斜率来判断。主意下面几点:
1. 直线斜率的计算,由于一条直线y=kx+b, 斜率k = (y2-y1) / (x2 - x1)。
2. 考虑到给定的点中可能存在重复的坐标,那么这些重复的点一定在一条直线上。
Java实现:
/**
* 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;
int len = points.length;
if(len <= 2) return len;
int max = 0;
for(int i = 0; i < len; i ++) {
HashMap<Double, Integer> mp = new HashMap<Double, Integer>();
int dup = 0;
int localMax = 1;
for(int j = 0; j < len; j ++) {
if(i == j) continue;
if(points[j].x == points[i].x && points[j].y == points[i].y) {
dup ++;
continue;
}
double tmp = (points[j].x == points[i].x) ? Integer.MAX_VALUE : (double)(points[j].y - points[i].y) / (points[j].x - points[i].x);
if(!mp.containsKey(tmp)) {
mp.put(tmp, 2);
}
else {
int t = mp.get(tmp);
mp.put(tmp, ++t);
}
}
for(Integer value : mp.values()) {
if(value > localMax) localMax = value;
}
localMax += dup;
if(localMax > max) max = localMax;
}
return max;
}
}