您的位置:首页 > 其它

LeetCode: Max Points on a Line

2014-02-22 14:56 435 查看
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Solution:

/**
* 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) {
//key is slope, value is the number of points in the line of a given slope
//this map will be reused
if (points.size() <= 1){
return points.size();
}
unordered_map<double, int> slopeMap;
int result = 0;
for (unsigned i = 0; i < points.size(); i++){
slopeMap.clear();

Point anchorPoint = points[i];
int dupPointCount = 0;
int dupLineCount = 1;
for (unsigned j = i + 1; j < points.size(); j++){
Point currentPoint = points[j];
//same point should be count in every line
if (anchorPoint.x == currentPoint.x && anchorPoint.y == currentPoint.y){
dupPointCount++;
} else {//not same point
double slope = std::numeric_limits<double>::infinity();
if (anchorPoint.x != currentPoint.x){//avoid divide 0 error
slope = (double)(anchorPoint.y - currentPoint.y) / (anchorPoint.x - currentPoint.x);
}
if (slopeMap.find(slope) == slopeMap.end()){//slope first appear
slopeMap[slope] = 1;
}
slopeMap[slope]++;
int currentLinePointCount = slopeMap[slope];
if (currentLinePointCount > dupLineCount){
dupLineCount = currentLinePointCount;
}
}
}
if (dupLineCount + dupPointCount > result){
result = dupLineCount + dupPointCount;
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: