LeetCode刷题笔录Max Points on a Line

本文详细介绍了如何通过遍历每个点并计算与其他点之间的斜率来找出二维平面上最多共线点数的方法。讨论了处理重复点及斜率为正无穷的情况,并提供了关键代码实现细节。

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


两个点是必然共线的。三个点共线的条件是任意两点间的斜率相等。那么解法来了:对于每一个点遍历剩下的所有点并计算斜率,用一个hashmap来记录同一个slope出现的次数,这些点就是共线的点。

注意两点:

1.给的点集中可能有重复的点,两个重复的点与任何斜率都共线,因此要单独考虑identical points的情况

2.斜率可以是正无穷

/**
 * 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) {
        Map<Float, Integer> slopeMap = new HashMap<Float, Integer>();
        if(points == null || points.length == 0)
            return 0;
        int max = 0;
        for(int i = 0; i < points.length; i++){
            slopeMap.clear();
            //to store potential identical duplicate points
            int identicals = 1;
            for(int j = 0; j < points.length; j++){
                if(i == j)
                    continue;
                int x1 = points[i].x;
                int y1 = points[i].y;
                int x2 = points[j].x;
                int y2 = points[j].y;
                
                //if the two points are identical
                if(x1 == x2 && y1 == y2){
                    identicals++;
                    continue;
                }
                Float slope = (x2 - x1 == 0) ? Float.MAX_VALUE : ((float)(y2 - y1) / (x2 - x1));
                if(slopeMap.containsKey(slope)){
                    int prevCount = slopeMap.get(slope);
                    slopeMap.put(slope, prevCount + 1);
                }
                else
                    slopeMap.put(slope, 1);
            }
            if(slopeMap.isEmpty()){
                max = Math.max(max, identicals);
            }
            for(Map.Entry<Float, Integer> entry : slopeMap.entrySet()){
                max = Math.max(max, entry.getValue() + identicals);
            }
        }
        
        return max;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值