您的位置:首页 > 编程语言 > C语言/C++

leetcode 日经贴,Cpp code -Max Points on a Line

2015-04-27 16:14 302 查看
Max Points on a 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 ans = 0;
double eps = 1e-6;
int n = points.size();
if (n <= 2) return n;
for (int i = 0; i < n; ++i) {
vector<double> angles;
int common = 0;
for (int j = 0; j < n; ++j) {
if (points[i].x == points[j].x && points[i].y == points[j].y) {
common++;
} else {
double dx = points[j].x - points[i].x;
double dy = points[j].y - points[i].y;
angles.push_back(atan2(dy, dx));
}
}
sort(angles.begin(), angles.end());
int same = 0;
for (int j = 0; j < angles.size(); ++j) {
if (j == 0 || abs(angles[j] - angles[j - 1]) > eps) {
ans = max(ans, same + common);
same = 1;
} else {
++same;
}
}
ans = max(ans, same + common);
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: