给定两个由N和M个整数组成的数组X []和Y [] ,使得有N条线平行于y轴, M条线平行于x轴,任务是找到具有唯一性的平方的总数可以从给定直线生成的尺寸。
Each integer(say a) in the array X[] denotes lines having equation x = a, parallel to
y-axis.
Each integer(say b) in the array Y[] denotes lines having equation y = b, parallel to
x-axis.
例子:
Input: X[] = {1, 3, 7}, Y[] = {1, 2, 4, 6}
Output: 2
Explanation:
3 lines are parallel to y-axis for x = 1, x = 3 and x = 7.
4 lines are parallel to x-axis for y = 2, y = 4, y = 6 and y = 1.
From the above figure, there are two possible squares of unique dimensions that are possible:
1) square ABDC (x = 1, x = 3, y = 4, y = 6), side = 2 units.
2) square BGHF (x = 3, x = 7, y = 2, y = 6), side = 4 units.
Input: X[] = {2, 6, 7, 8}, Y[] = {1, 3, 5, 7}
Output: 3
天真的方法:最简单的方法是检查每个可能的垂直尺寸,如果存在相等的水平尺寸。借助地图可以减少这种方法的时间复杂度。通过使用地图,我们可以获得所有不同的垂直/水平尺寸。
i>时间复杂度: O((N 2 )* log N)
辅助空间: O(N)
高效的方法:为了优化上述方法,我们的想法是借助位集生成所有可能的尺寸。请按照以下步骤解决此问题:
- 分别初始化数组X []和Y []的水平和垂直线的位集。
- 在位集中设置垂直线和水平线的位置。
- 维护另一个位集hdiff和vdiff ,这些位集存储正方形的不同可能尺寸。可以通过移动原始位集中的设置位来获得尺寸。
- 完成上述步骤后,平方的唯一计数是hdiff和vdiff中公共元素的计数,该计数由(hdiff&vdiff).count()计算。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
const int N = 100;
// Function to find the number of
// unique squares
int countSquares(int* hor, int* ver,
int n, int m)
{
// Positions of the X[] and Y[]
// are set in the bitsets hpos
// and vpos respectively
bitset hpos, vpos;
for (int i = 0; i < n; ++i) {
hpos.set(hor[i]);
}
for (int i = 0; i < m; ++i) {
vpos.set(ver[i]);
}
// Stores all possible sides of the
// square are set in the bitsets
// having difference hdiff & vdiff
bitset hdiff, vdiff;
for (int i = 0; i < n; ++i) {
hdiff = hdiff | (hpos >> hor[i]);
}
for (int i = 0; i < m; ++i) {
vdiff = vdiff | (vpos >> ver[i]);
}
// Finding the number of square
// sides which are common to both
int common = (hdiff & vdiff).count();
// Print the count of squares
cout << common - 1;
}
// Driver Code
int main()
{
// Given horizontal line segments
int X[] = { 1, 3, 7 };
// Given vertical line segments
int Y[] = { 1, 2, 4, 6 };
int N = (sizeof(X) / sizeof(X[0]));
int M = (sizeof(Y) / sizeof(Y[0]));
// Function Call
countSquares(X, Y, N, M);
return 0;
}
2
时间复杂度: O(N + M)
辅助空间: O(maxE),其中maxE是数组X []和Y []中的最大元素。