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

分析:

试想一下,所有跟跟原点的斜率相同的点都在同一条直线上。同理,所有跟某一个固定点斜率相同的点都在同一条直线上。那么我们就用double for loop,其中外层的loop来遍历所有点,每次循环,就找到一个固定点;内层循环从i+1开始,找到所有跟points[i]斜率相同的点(只需要找i右边的即可),然后将count保存在一个map上。需要注意的是,有可能会有相同的点,要注意处理。

代码:(O(n^2))

class Solution {
public:
	int maxPoints(vector<Point> &points) {
		int result = 0;
		map<double, int> counts;
		for (int i = 0; i < points.size(); i ++) {
			counts.clear();
			int same_point = 0;
			int curretn_max = 1;
			for (int j = i + 1; j < points.size(); j ++) {
				double slop = std::numeric_limits<double>::infinity();

				if (points[j].x != points[i].x)
					slop = 1.0 * (points[j].y - points[i].y) / (points[j].x - points[i].x);
				else if (points[j].y == points[i].y) {
					same_point ++;
					continue;
				}

				if (counts.find(slop) != counts.end())
					counts[slop] ++;

				else
					counts[slop] = 2;
				curretn_max = max(curretn_max, counts[slop]);
			}
			result = max(result, curretn_max + same_point);
		}
		return result;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值