149. Max Points on a Line

本文介绍了一种解决二维平面上找到最多共线点数量的方法。通过计算每一对点之间的斜率并对其进行排序,找出拥有相同斜率的最长序列,以此确定最大共线点数。文章提供了完整的Java实现代码。

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

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



知道思路:先对每个节点求出其他节点到此节点的斜率,在排序,找最长相同斜率的个数,但是尴尬的是竟然写了一个多小时,也是醉了

import java.util.Arrays;

public class Solution {
    public int maxPoints(Point[] points) {
    	if(points == null || points.length == 0)	return 0;
    	if(points.length == 1)						return 1;
    	
    	double[] slops = new double[points.length-1];
        int max = 2;
        
        for(Point start : points) {
        	int cnt = 0, same = 0;
        	for(Point end : points) {
        		if(start.x == end.x && start.y == end.y) 	same ++;
        		else if(start.x == end.x)					slops[cnt++] = Integer.MAX_VALUE;
        		else										slops[cnt++] = (end.y - start.y + 0.0) / (end.x - start.x);
        	}
        	
        	Arrays.sort(slops, 0, cnt);
        	
        	if(same == points.length)	return points.length;
        	
        	for(int i=0; i<cnt-1; i++) {
        		int count = 1 + same;
        		while(i<cnt-1 && slops[i] == slops[i+1])	{
        			count++;
        			i++;
        		}
        		if(count > max) {
        			max = count;
        		}
        	}
        }
        
    	return max;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值