您的位置:首页 > 其它

LeetCode - Max Points on a Line

2013-12-10 15:00 417 查看
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.

/**
* 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 result = 0;
for (int i = 0; i < points.size(); ++i) {
std::unordered_map<string, int> number;
int mx = 0;
int same = 1;
for (int j = i+1; j < points.size(); ++j) {
int x = points[j].x - points[i].x;
int y = points[j].y - points[i].y;

int g = gcd(x, y);

if (g !=0) {
x /= g;
y /= g;
mx = max(mx, ++number[to_string(x) + " " + to_string(y)]);
}
else {
same++;
continue;
}
}

result = max(result, (mx + same));
}

return result;
}

int gcd(int a, int b) {
return a? a/abs(a)*abs(gcd(b%a, a)) : b;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: