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;
}
};