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.

Iterate over each point, calculate the slope of this point and each other point, and use a hashmap to store the slope and the number of points on that line. Note the case when there are duplicate points, and when the line is vertical. Need to add 0.0 when calculating slope to solve - 0.0 != 0.0 problem.

/**
 * 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) {
        if (points == null || points.length == 0) {
            return 0;
        }
        
        HashMap<Double, Integer> map = new HashMap<Double, Integer>();
        int max = 1;
        for (int i = 0; i < points.length; i++) {
            map.clear();
            int dup = 0;
            for (int j = i + 1; j < points.length; j++) {
            	if ((points[i].x == points[j].x) && (points[i].y == points[j].y)) {
            		dup++;
            		continue;
            	}
            	
            	double k;
            	if (points[i].x - points[j].x == 0) {
            		k = Integer.MAX_VALUE;
            	} else {
            		k = 0.0 + (double) (points[i].y - points[j].y) / (double) (points[i].x - points[j].x);
            	}
            	
                if (map.containsKey(k) || points[i] == points[j]) {
                    map.put(k, map.get(k) + 1);
                } else {
                    map.put(k, 2);
                }
            }
            
            int count = 1;
            for (int num : map.values()) {
                count = count > num ? count : num;
            }
            count += dup;
            
            max = max > count ? max : count;
        }
        
        return max;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值