Question
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution
这道题用穷举法求解,时间复杂度为O(n^2)。但是要注意几个细节,如果包含的点数小于等于2,那么直接返回点数。
如果第三个点和前面两个点中的一个相等,那么直接在总数上累加1。如果第三个点和前面两个点的横坐标都一样,那么直接在总数上累加1,如果只和其中一个一样,那么直接计算下一个点。如果两个都不一样,那么就开始计算斜率是否相等,相等的话,总数就累加1,反之。
Code
/**
* Definition for a point.
* 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) {
if (points.size() <= 2)
return points.size();
int maxNumbers = 2;
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
int count = 2;
for (int k = 0; k < points.size(); k++) {
if (k == i || k == j)
continue;
// 重叠
if ((points[k].x == points[i].x && points[k].y == points[i].y) ||
(points[k].x == points[j].x && points[k].y == points[j].y)) {
count++;
if (count > maxNumbers)
maxNumbers = count;
continue;
}
// 横坐标一样,相减为0,不能计算斜率
if (points[k].x == points[j].x) {
if (points[j].x == points[i].x) {
count++;
if (count > maxNumbers)
maxNumbers = count;
continue;
} else
continue;
} else if (points[j].x == points[i].x) {
continue;
}
// 计算斜率
if ((points[k].y - points[j].y) / (float)(points[k].x - points[j].x) ==
(points[j].y - points[i].y) / (float)(points[j].x - points[i].x))
count++;
if (count > maxNumbers)
maxNumbers = count;
}
}
}
return maxNumbers;
}
};