Leetcode: 149. Max Points on a Line

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);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值