Max Points on a Line

本文介绍了一种算法,用于在一个二维平面上找出最多共线的点数。通过遍历并考虑斜率和重复节点,该算法有效解决了此问题。详细代码和逻辑分析供读者参考。

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

题目:

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

解答:

遍历,注意重复节点和斜率为0的情况。

代码:

class Solution {
public:
	int maxPoints(vector<Point> &points) {
		map<float, int> mp;
		int i, j;
		int same = 0;
		int max = 0;
		for (i = 0; i < points.size(); i++)
		{
			same = 1;
			mp.clear();
			mp[INT_MAX] = 0;
			for (int j = 0; j < points.size(); j++)
			{
				if (i == j)
					continue;
				if (points[i].x == points[j].x && points[i].y == points[j].y)
				{
					same++;
					continue;  //这里 漏写continue,导致后面重复计算
				}
				float k = (points[i].x == points[j].x ? INT_MAX : (float)(points[i].y - points[j].y) / (float)(points[i].x - points[j].x));  //这里float k误写成int k 调试了一个小时,笨啊
				++mp[k];

			}
			for (map<float, int>::iterator it = mp.begin(); it != mp.end(); it++)
			{
				if (it->second + same > max)
					max = it->second + same;
			}
		}
		return max;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值