Leetcode习题:Max Points On a Line

本文介绍了一种寻找平面上共线点的最大数量的算法。通过计算每两点间斜率并利用哈希表记录斜率出现次数,该算法能有效地找出具有相同斜率的点集合,即共线点。特别地,算法考虑了重复点的情况。
/**
 * 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 {
     
         // 1. consider same points
    public int maxPoints(Point[] points) {
        
        int maxCount = points.length == 0 ? 0: 1;
        
        for(int i = 0; i<points.length; i++){
            
            Map<Double, Integer> slopes = new HashMap<Double, Integer>();
            
            int equalPoints = 0;
            
            for( int j = 0; j < points.length; j++ ){
                if(j == i){
                    continue;
                }
                
                if(points[i].x == points[j].x && points[i].y == points[j].y){
                    equalPoints++;
                }else{
                    double k = ((double)(points[j].y - points[i].y))/(points[j].x - points[i].x);
                    if(slopes.containsKey(k)){
                        slopes.put(k, slopes.get(k)+1);
                    }else{
                        slopes.put(k,2);
                    }
                }
                
                if(maxCount < equalPoints + 1){
                    maxCount = equalPoints + 1;
                }
                
            }
            
            for(Double slope: slopes.keySet()){
                if(slopes.get(slope) + equalPoints > maxCount){
                    maxCount = slopes.get(slope) + equalPoints;
                }
            }
        }
        
        return maxCount;
    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值