给定两个由 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[] 中的最大元素。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live