LeetCode149 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.

Example 1:

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4

Example 2:

Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

题源:here;完整实现:here

思路:

这个问题其实就是图像处理中的霍夫变换求最长直线的问题,但是用霍夫变换来处理这个问题有点复杂。我们换个角度:我们每个点都找一下,看看有多少点和它在一条直线上(本文查考)。注意,为了避免斜率问题,我们保存的是计算斜率时的坐标差,为了使1,2;2,4这样的坐标差在一个集合中出现,我们需要找到他们的GCD。具体代码如下:

class Solution {
public:
	int maxPoints(vector<Point>& points) {
		if (points.size() <= 1) return points.size();
		int res = 0;
		for (int i = 0; i < int(points.size()); i++) {
			map<pair<int, int>, int> hash;
			int duplicate = 0;
			for (int j = 0; j < int(points.size()); j++) {
				if (points[i].x == points[j].x && points[i].y == points[j].y) {
					duplicate++;
					continue;
				}
				int dx = points[i].x - points[j].x;
				int dy = points[i].y - points[j].y;
				int gcd = GCD(dx, dy);
				hash[{dx / gcd, dy / gcd}]++;
			}
			res = max(res, duplicate);
			for (auto it = hash.begin(); it != hash.end();it++) {
				res = max(res, it->second + duplicate);
			}
		}
		return res;
	}
	int GCD(int x, int y) {
		return y ? GCD(y, x % y) : x;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值