从右到左计算当前索引中的数据结构中的元素数,并打印每个元素的计数
Counting the no of elements in a data structure from the current index from right to left and printing the count for each element
城市中存在各种信号塔。塔以直线水平线(从左到右)排列,每个塔在从右到左方向上传输信号。如果 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
击败60
和70
,但我们被击败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 拍)。
希望这能回答你的问题。
相关文章:
- 从控制台中删除最后打印的元素
- 数组元素打印的递归方法
- 打印所有链表的元素 (C++)
- 更新的矢量元素不打印
- 打印矢量数组中的所有元素
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 如何在c ++中打印给定桶号的所有元素unordered_set?
- 为什么平均打印数组元素比打印单个对象慢C++?
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 使用 <list> (错误 C2760) 打印队列的元素
- 使用哈希图打印第一个重复元素;
- 打印二叉树中的常见元素
- 打印无序映射的第二个元素,即集合
- 打印所有儿童树元素的最佳算法?
- 类中的 C++ 全局映射,不要打印 map 元素
- 为什么数组不打印第一个元素?
- C++ Expat 仅打印元素的第一个字母和标签中的数据
- 打印出对象向量中的每个元素C++
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 按升序打印矢量的所有元素直到它为空而没有重复项的最有效方法是什么?