从右到左计算当前索引中的数据结构中的元素数,并打印每个元素的计数

Counting the no of elements in a data structure from the current index from right to left and printing the count for each element

本文关键字:元素 打印 数据结构 计算 索引 从右到左      更新时间:2023-10-16

城市中存在各种信号塔。塔以直线水平线(从左到右)排列,每个塔在从右到左方向上传输信号。如果 A 塔位于 B 塔左侧且 A 塔高于 B 塔,则 A 塔将阻止 B 塔的信号。因此,给定塔的信号范围可以定义为:

{(位于给定塔左侧且高度小于或等于给定塔的高度的连续塔的数量)+ 1}。

#include <iostream>
#include <vector>
using namespace std;
vector<int> res;
void recursion(int a[],int x)
{
if (x >= 0)
{// Taking the last element of the array as the max element
int max = a[x], count = 0;
for (int i = x; i >= 0; i--)
{//Comparing the max with all the elements in the array
if (max >= a[i])
{
count++;
}
else
{
break;
}
}
//Pushing the count of the current element in the vector.
res.push_back(count);
x = x - 1;
recursion(a, x);
}
}
int main() {
int TestCase, n;
cin >> TestCase;
for (int l = 0; l < TestCase; l++)
{
cin >> n;
int * arr = new int[n];
//Getting the elements
for (int j = 0; j < n; j++)
{
cin >> arr[j];
}
recursion(arr, n-1);
//Iterating through the vector in reverse manner and printing 
//the result.
for (auto it = res.rbegin(); it != res.rend(); ++it)
{
cout << *it << " ";
}
delete[] arr;
}
return 0;
}

第一行包含一个整数 T,指定测试用例的数量。

第二行包含一个整数 n,指定塔的数量。

第三行包含 n 个空格分隔的整数 (H[i]),表示高度 每座塔。

打印每个塔的范围(用空格分隔)。

示例输入

1
7
100 80 60 70 60 75 85

示例输出

1 1 1 2 1 4 6

我的解决方案是正确的,但时间复杂性是问题所在。有没有办法降低时间复杂度?

  • 要计算向左发射信号的每个塔的范围,您需要使用stack结构。

  • 我们在数组中从左到右,我们将每个元素存储在堆栈中。现在,我们在堆栈中插入塔。

  • 每当我们到达下一个塔时,我们都会不断从高度小于当前塔的堆栈中弹出塔。完成后,我们将在堆栈中插入当前塔,依此类推,用于后续塔。

  • 这里需要注意的重要一点是,当您将它们插入堆栈中时,您也需要存储被当前塔击败的塔的编号。

  • 每个塔的答案(基本情况除外)是否定的。 被击败的塔数 + 1。

  • 下面{}内的整数是当前塔击败的塔的编号。

例:

100 80 60 70 60 75 85
^
  • 当我们在100时,堆栈是空的,因此我们将其插入堆栈并打印答案作为1将其视为基本答案。
Current stack: 100{0}
80 60 70 60 75 85
^
  • 现在,让我们测试一下80。当塔80向左发出信号时,我们会不断从堆栈中排便小于80的所有元素,并在得到一个块(即具有相同或更高高度的塔)时停止。在这种情况下,我们停留在100本身。因此,信号覆盖的距离是1.
Current stack: 100{0} 80{0}
60 70 60 75 85
^
  • 现在,60的答案又1了。
Current stack: 100{0} 80{0} 70{1}
70 60 75 85
^
  • 对于70,信号跳动60并在80停止,所以70的答案是否定的。 塔被击败的塔数 + 1,因此 1 + 1 = 2。
Current stack: 100{0} 80{0} 70{1} 60{0}
60 75 85
^
  • 60不会击败任何人,所以 0 + 1 = 1。
Current stack: 100{0} 80{0} 75{3}
75 85
^
  • 75击败6070,但我们被击败3塔,因为我们没有添加。 被较小的塔击败的塔+塔本身也是如此。所以,简单来说,

60{0}是 1(60 本身)+ 0(被60本身击败的塔数)+ 1(70 本身)+ 1(被70本身击败的塔数)= 1 + 1 + 1 = 3。75 的答案是 3 + 1 = 4。

Current stack: 100{0} 85{5}
85
^
  • 85的答案是 5 + 1 = 6 => 1(75 拍)+ 3(75 拍)+ 1(80 拍)+ 0(80 拍)。

希望这能回答你的问题。