URL
https://leetcode.com/problems/max-points-on-a-line/description/
描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
解题思路
遍历所有点,计算出每一个点与其他的点的斜率,找出斜率相同的点最大数量。只是在计算斜率的时候需要一些技巧(见代码中getSlope方法),下面给出代码。
代码示例
class Solution {
public int maxPoints(Point[] points) {
int res = 0;
if(points == null || points.length == 0) return res;
for(int i=0;i<points.length-1;i++){
Map<String,Integer> cache = new HashMap<>();
int overlap = 0;
int tempCount = 0;
int tempMax = 0;
for(int j=i+1;j<points.length;j++){
if(equal(points[i],points[j])){
overlap++;
continue;
}
String slope = getSlope(points[i],points[j]);
if(cache.containsKey(slope)){
tempCount = cache.get(slope);
}else{
tempCount = 0;
}
cache.put(slope,++tempCount);
tempMax = Math.max(tempMax,tempCount);
}
res = Math.max(res,tempMax+overlap);
}
return res+1;
}
private boolean equal(Point p,Point q){
return p.x==q.x && p.y == q.y;
}
private String getSlope(Point p,Point q){
int xx = p.x - q.x;
int yy = p.y - q.y;
int gcd = getGCD(yy,xx);
return String.valueOf(xx/gcd)+"-"+String.valueOf(yy/gcd);
}
private int getGCD(int x,int y){
if(y==0) return x;
return getGCD(y,x%y);
}
}