[LeetCode] Max Points on a Line

本文介绍了一个算法问题:给定二维平面上的n个点,如何找出共线点的最大数量。通过计算每两个点之间的斜率并使用哈希表存储,可以有效地解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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


分析:

一个点加一个斜率,就可以唯一的确定一条直线。所以我们对每个点,都计算一下该点和其他点连线的斜率,这样对于这个点来说,相同斜率的直线有多少条,就意味着有多少个点在同一条直线上,因为这些直线是相同的。另外,如果计算过点A和点B的直线,当算到点B时,就不用再和A连线了,因为AB这条直线上的点数已经都计算过了。这里,我们用哈希表,以斜率为key,记录有多少重复直线。需要注意的是,Double是有正0和负0的区分的,所以我们要用if(slope * slope == 0) slope = 0;把负0都变成正0。


代码:

import java.util.HashMap;

class Point {
	int x, y;
	
	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

public class MaxPointsOnALine {
	public int maxPoints(Point[] points) {
		if(points.length <= 1) return points.length;
		int max = Integer.MIN_VALUE;
		for(int i = 0; i < points.length; i++) {
			//过当前点的直线组成的哈希表,斜率为key
			HashMap<Double, Integer> lines = new HashMap<Double, Integer>();
			int vertical = 0, same = 1, currMax = 0;
			for(int j = i + 1; j < points.length; j++) {
				//统计相同的点
				if(points[i].x == points[j].x && points[i].y == points[j].y) {
					same++;
					continue;
				}
				//统计斜率为无穷的点,它们都在一条直线上
				if(points[i].x == points[j].x) {
					vertical++;
					continue;
				}
				//计算连线的斜率
				double slope = ((double)points[i].y - (double)points[j].y) / ((double)points[i].x - (double)points[j].x);
				//修正负0
				if(slope * slope == 0) slope = 0;
				lines.put(slope, lines.containsKey(slope) ? lines.get(slope) + 1 : 1);
				currMax = Math.max(currMax, lines.get(slope));
			}
			//经过该点的直线上最多的点数,我们在无穷斜率和正常斜率中选较大的,还要加上相同的点数
			currMax = Math.max(vertical, currMax) + same;
			max = Math.max(currMax, max);
		}
		return max;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值