代码真的是太丑了,刚开始的时候思路简单,利用向量共线的原理,三点A(x1, y1) B(x2, b2) C(x3, y3),如果(x3 - x1) * (y2 - y1) == (x2 - x1) * (y3 - y1),那么ABC三点共线。于是先在集合里任取两点,再遍历第三点,判断是否共线即可。
然而测试用例里陷进很多,相同的点在计算时是需要重复计数的,然而,如果相同的点作为最初选定的点,那么依照上面的公式,集合里所有点都会被算为和这两点共线,因此这种情况必须排除掉。同时,测试用例里又有[(1, 1), (1, 1), (1, 1)]这种的,如果粗暴地直接跳过相同点为最初两点的话,这种情况又会被排除在外。所以我不得不写了个很丑的代码处理这种情况……
/**
* 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) {
int n = points.size();
if (n == 0)
return 0;
if (n == 1)
return 1;
int max = 2;
for (int i = 0; i < n; ++i) {
int x1 = points[i].x;
int y1 = points[i].y;
for (int j = i + 1; j < n; ++j) {
int x2 = points[j].x;
int y2 = points[j].y;
int m = 0;
if (x1 != x2 || y1 != y2)
for (int k = 0; k < n; ++k) {
int x3 = points[k].x;
int y3 = points[k].y;
if ((x3 - x1) * (y2 - y1) == (x2 - x1) * (y3 - y1))
m++;
}
else {
for (int k = 0; k < n; ++k) {
int x3 = points[k].x;
int y3 = points[k].y;
if (x3 == x1 && y3 == y1)
m++;
}
}
if (m > max)
max = m;
}
}
return max;
}
};
http://oj.leetcode.com/problems/max-points-on-a-line/