[leetcode-149]Max Points on a Line(java)

问题描述:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

分析:这道题首先明确,如何确定在同一条直线上?那如果固定一个点,那就是通过某点与该点的向量决定,如果向量一样,那代表同一条直线。但是向量是由(x,y)决定,但是这个值不能用作hashmap的key,所以退而使用斜率。其中斜率要注意x = 0的情况,即将vertical的数单独计算。
同时还有一个问题是重复的问题,之前的思路是如果重复,那就给通过该节点向量中的每个向量的计数+1,但是这样带来了一些问题,当新添加向量时,然后确定计数值。
后来为了简单起见,当出现重复的时候,直接将一个duplicate值更新。然后当处理完所有的节点之后,再对所有的向量值进行一次遍历,然后将value+dulplicate与max比较,并对max更新。

代码如下:324ms

/**
 * 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) {
        int length = points.length;
        if(length<=2)
            return  length;

        int max = 2;
        HashMap<Double,Integer> maps = new HashMap<>();
        for(int i = 0;i<length;i++){
            maps.clear();
            Point now = points[i];
            int dulplicate = 1;
            int vertical = 0;

            for(int j = i+1;j<length;j++){
                Point cmp = points[j];
                if(now.x == cmp.x && now.y == cmp.y)
                    dulplicate++;
                else if(now.x==cmp.x){
                    vertical++;
                }else{
                    double slope = (cmp.y==now.y)?0.0:(1.0)*(cmp.y-now.y)/(cmp.x-now.x);
                    if(maps.containsKey(slope)){
                        maps.put(slope,maps.get(slope)+1);
                    }else
                        maps.put(slope,1);
                }
            }
            //遍历hashmap
            Iterator iterator = maps.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry entry = (Map.Entry)iterator.next();
                int value = (int)entry.getValue();
                if(value+dulplicate>max)
                    max = value+dulplicate;
            }
            max = Math.max(vertical+dulplicate,max);
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值