LeetCode - Max Points on a Line

本文介绍了一种算法,用于找出二维平面上最多有多少个点位于同一直线上。通过计算点之间的斜率并使用哈希表存储斜率出现的次数,该算法能够在O(n^2)的时间复杂度内解决问题。

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

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.


 通过计算斜率来判断是否在一条直线上,要注意首尾点可能重复,另外java double类型的 0 和 -0是不一样的,最后O(n平方)过了,O(2n平方)超时了,
public class Solution {
    public int maxPoints(Point[] points) {
      int result = 0;
		
		HashMap<Double,Integer> v = new HashMap<Double,Integer>();
		for(int i = 0; i < points.length ; ++i){
			int total = 0;
			int special = 0;
			int multiple = 1;
			for(int j = i+1 ; j < points.length ; ++j){
				if(points[j].x != points[i].x ){
					double ratio = (double)(points[j].y - points[i].y)/(double)(points[j].x - points[i].x);
					if((Math.abs(ratio) - 0) < 0.0000001){
						ratio = 0d;
					}
					v.put(ratio,v.get(ratio) == null?1:v.get(ratio)+1);
					int size = v.get(ratio);
					if(total < size ){
						total = size;
					}
				}else if(points[j].x == points[i].x && points[j].y != points[i].y){
					special ++;
				}else{
					multiple ++;
				}
			}
			v.clear();
			if(result < special + multiple){
				result = special + multiple;
			}
			if(result < total + multiple){
				result = total + multiple;
			}
		}
		return result;
    }
}

Submission Result: Accepted

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值