您的位置:首页 > 职场人生

leetcode 149. Max Points on a Line

2017-10-19 21:38 441 查看
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题意:给一个二维平面,上面有好多点,有横纵坐标,找出一条直线,使得这条线上的点数量最多。
这是当时百度春招实习时面试官问过的一道题,当时虽然没有写代码。但是之后回来也没有再看过。今天刷题,突然发现是LeetCode原题,hard难度。不仅感慨,长叹一声。然后今天舍友视频面试小红书的时候也被问到了这道题。所以就做一下记录吧。

思路的话就是:一般就是求斜率,遍历所有的点,但是有几个地方需要注意一些,因为这些点可能有重合的!!!还有就是求斜率的时候注意垂直X轴的那些点,斜率是无穷,单独计算。
public class Solution {
public int maxPoints(Point[] points) {
if(points.length <= 0) return 0;
if(points.length <= 2) return points.length;
int result = 0;
for(int i = 0; i < points.length; i++){
//针对每个点,用hash表存储和其他点所能组成的各种斜率情况,求一个最大
HashMap<Double, Integer> hm = new HashMap<Double, Integer>();
int samex = 1;//默认自己
int samep = 0;
///以每个点作为起点,求与其他点的斜率的最大值
for(int j = 0; j < points.length; j++){
if(j != i){
if((points[j].x == points[i].x) && (points[j].y == points[i].y)){
samep++;
}
///垂直X轴的点们
if(points[j].x == points[i].x){
samex++;
continue;
}
//开始计算斜率
//double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
double k = (double)(points[j].x - points[i].x) / (double)(points[j].y - points[i].y);
///存在的话直接加1
if(hm.containsKey(k)){
hm.put(k,hm.get(k) + 1);
}else{
hm.put(k, 2);////包含当前点,和遍历到的点
}
//每次都求一个最大值,求每个不同斜率的最大值
result = Math.max(result, hm.get(k) + samep);
}
}
///每次需要比较一下在一条直线,垂直X轴上的点。。。
result = Math.max(result, samex);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试