您的位置:首页 > 其它

LeetCode-Max Points on a Line

2014-07-28 12:49 344 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.

Solution:

Code:

<span style="font-size:14px;">/**
* 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) {
const int length = points.size();
if (length == 0 || length == 1 || length == 2) return length;
int result = 1;
int duplicate;
int maxLine;
unordered_map<double, int> hashTable;
for (int i = 0; i < length; ++i) {
hashTable.clear();
duplicate = 0;
maxLine = 0;
for (int j = 0; j < length; ++j) {
if (points[i].x == points[j].x && points[i].y == points[j].y) ++duplicate;
else if (points[i].x == points[j].x && points[i].y != points[j].y) {
++hashTable[INT_MAX];
maxLine = max(maxLine, hashTable[INT_MAX]);
} else {
++hashTable[(double)(points[j].y-points[i].y)/(points[j].x-points[i].x)];
maxLine = max(maxLine, hashTable[(double)(points[j].y-points[i].y)/(points[j].x-points[i].x)]);
}
}
result = max(result, duplicate+maxLine);
}
return result;
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息