题目描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
给定二维平面上n个点,找出位于同一直线上的点的最大数目。
思路:
位于同一直线:斜率((y2-y1) / (x2-x1))相同。
1、用双重循环即可解决问题,外层循环依次以每个点作为基准,内层循环中用其余各点与固定点计算斜率,垂直和重合情况分别考虑。
2、对于外层循环中每个点,定义一个map,key:斜率(Double) value:相同斜率出现的次数(Integer)。
3、内层循环走完一轮回,从map中得出与固定点在同一直线上点的最大数量,即为max。
4、内层循环走完一轮回,更新max的值。
5、最后max为所求。
边界条件:
只给出0个点或者一个点:结果位于同一直线上点的最大数量为0或1;
垂直 (x2 = x1) :斜率不存在;
重合 (y2 = y1, x2=x1) :给出的n个点坐标,可能有坐标相同的点,导致重合的情况;
其他正常情况。
Java代码:
import java.util.HashMap;
import java.util.Map;
class Point {
int x;
int y;
public Point() {
this.x = 0;
this.y = 0;
}
public Point (int x, int y) {
this.x = x;
this.y = y;
}
}
public class Solution {
public static int maxPoints(Point[] points) {
int len = points.length;
if(len < 2) {
return len;//考虑到只有0/1个点的情况
}
int max = 0;
for(int i = 0; i < len ; i ++) {
Map<Double,Integer> map = new HashMap<Double,Integer>();
int cz = 0;//x1 = x2,垂直即斜率不存在的情况
int ch = 0;// 给出的n个点可能有重合的点
for(int j = 0; j < len ; j ++) {
if(i == j) continue;
if(points[i].x == points[j].x) {
if(points[i].y == points[j].y) {
ch ++;
}else {
cz ++;
}
}
else {
double key = 1.0 * (points[i].y - points[j].y)/(points[i].x - points[j].x);
map.put(key, map.get(key) == null ? 1 : map.get(key) + 1);
// if(!map.containsKey(key))
// {
// map.put(key, 1);
// }
// else {
// map.put(key, map.get(key)+1);
// } //此if-else用上面的一条语句即可解决
}
}
int temp = cz;
for(double k : map.keySet()) {
temp = temp > map.get(k)? temp : map.get(k);
}
max = max > temp + ch + 1 ? max : temp + ch + 1;
}
return max;
}
}