这个问题是关于从一堆点中找到共线点。
首先,我不明白slopeMap
和无序地图怎么样?不是地图只假设有一个键和一个值(map<key, value>
)?在这个特定的代码中
unordered_map<pair<int, int>, int,boost::
hash<pair<int, int> > > slopeMap;
根据我的理解,它有一对作为键和一个后面的int,它应该是值,但那么它并不完全在那里结束?
完整代码:
using namespace std;
// method to find maximum colinear point
int maxPointOnSameLine(vector< pair<int, int> > points)
{
int N = points.size();
if (N < 2)
return N;
int maxPoint = 0;
int curMax, overlapPoints, verticalPoints;
// here since we are using unordered_map
// which is based on hash function
//But by default we don't have hash function for pairs
//so we'll use hash function defined in Boost library
unordered_map<pair<int, int>, int,boost::
hash<pair<int, int> > > slopeMap;
// looping for each point
for (int i = 0; i < N; i++)
{
curMax = overlapPoints = verticalPoints = 0;
// looping from i + 1 to ignore same pair again
for (int j = i + 1; j < N; j++)
{
// If both point are equal then just
// increase overlapPoint count
if (points[i] == points[j])
overlapPoints++;
// If x co-ordinate is same, then both
// point are vertical to each other
else if (points[i].first == points[j].first)
verticalPoints++;
else
{
int yDif = points[j].second - points[i].second;
int xDif = points[j].first - points[i].first;
int g = __gcd(xDif, yDif);
// reducing the difference by their gcd
yDif /= g;
xDif /= g;
// increasing the frequency of current slope
// in map
slopeMap[make_pair(yDif, xDif)]++;
curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]);
}
curMax = max(curMax, verticalPoints);
}
// updating global maximum by current point's maximum
maxPoint = max(maxPoint, curMax + overlapPoints + 1);
// printf("maximum colinear point
// which contains current point
// are : %d\n", curMax + overlapPoints + 1);
slopeMap.clear();
}
return maxPoint;
}
//驱动程序代码
int main()
{
const int N = 6;
int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2},
{3, 3}, {3, 4}};
vector< pair<int, int> > points;
for (int i = 0; i < N; i++)
points.push_back(make_pair(arr[i][0], arr[i][1]));
cout << maxPointOnSameLine(points) << endl;
return 0;
}
哪里
Input : points[] = {-1, 1}, {0, 0}, {1, 1},
{2, 2}, {3, 3}, {3, 4}
Output : 4
Then maximum number of point which lie on same
line are 4, those point are {0, 0}, {1, 1}, {2, 2},
{3, 3}
我还想要一个基于逻辑的建议。我怎么能修改这个代码,以便不是返回一个定义最大点数colinear的数字,而是实际存储我以后可能使用的某种形式的数据结构的共线点?
不是地图只假设有一个键和一个值(地图)?
实际上,std::unordered_map有几个额外的模板参数。第三个参数是哈希。
我怎么能修改这个代码,以便不是返回一个定义最大点数colinear的数字,而是实际存储我以后可能使用的某种形式的数据结构的共线点?
使用整数坐标比使用浮点更容易(由于精度问题)。我假设你有一个2D点p
阵列。一种方法是,对于每两对点p[i]
和p[j]
,让你的密钥成对dX,dY减少到最低形式(其中dX = p[j].x - p[i].x
和dY = p[j].y - p[i].y
)。然后你的价值可能是一个std::set<int>
,其中包含匹配的指数i
和j
。