[LeetCode]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.


本题关键是找到在同一条线的点的寻找,这里寻找的原则就是,如果两个点都与一个点所得出的斜率相等,那么这两个点在同一条直线上。

开始的思路是遍历所有直线的可能,然后遍历所有的点检查是否在直线上,显然复杂度太高了。


参考:http://blog.youkuaiyun.com/doc_sgl/article/details/17103427


这里面需要考虑一些特殊情况,斜率无穷大的情况:

开始我的思路是判断如果出现x1-x2 == 0,那么就求斜率倒数,后来发现参考文章中所提出的直接判断这种的情况的key为INT_MAX的方法更加方便简介。

参考文章用的是:unordered_map,我直接用map,这方面不太懂区别,有待学习。


#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

struct Point {
	int x;
	int y;
	Point() : x(0), y(0) {}
	Point(int a, int b) : x(a), y(b) {}
};

class Solution {
public:
	int maxPoints(vector<Point> &points)
	{
		int duplex = 1, max = 0;
		float k;
		map<float, int> mp;
		map<float, int>::iterator mit;
		vector<Point>::iterator it1 = points.begin();
		vector<Point>::iterator it2 = points.begin() + 1;
		for (it1 = points.begin(); it1 != points.end(); it1++)
		{
			mp.clear();
			mp[INT_MAX] = 0;
			duplex = 1;
			for (it2 = points.begin(); it2 != points.end(); it2++)
			{
				if (it1 == it2)
					continue;
				if (it1->x == it2->x && it1->y == it2->y)
				{
					duplex++;
					continue;
				}
				if (it1->x == it2->x)
				{
					mp[INT_MAX]++;
				}
				else
				{
					k = (float)(it1->y - it2->y) / (it1->x - it2->x);
					mp[k]++;
				}
			}
			for (mit = mp.begin(); mit != mp.end(); mit++)
			{
				if ((mit->second + duplex) > max)
					max = mit->second + duplex;
			}
		}
		return max;
	}
};


int main()
{
	Solution aa;
	vector<Point> pp = { Point(1, 1), Point(2, 2), Point(3, 3), Point(4, 4) };
	cout << aa.maxPoints(pp) << endl;

	system("PAUSE");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值