
下一个较小的元素是其后第一个较小元素的元素。让我们看一个例子。
arr = [1, 2, 3, 5, 4]
5 的下一个较小元素是 4,元素 1、2 的下一个较小元素是, 3 为 -1,因为它们后面没有更小的元素。
用随机数初始化数组
立即学习“C++免费学习笔记(深入)”;
初始化堆栈。
将第一个元素添加到堆栈中。
迭代遍历数组的元素。
如果栈为空,则将当前元素添加到栈中。
当当前元素小于堆栈顶部元素时。
打印顶部元素,并将下一个较小元素作为当前元素。 p>
弹出顶部元素。
将元素添加到堆栈中。
当堆栈不为空时。
将下一个较小元素的元素打印为-1.
下面是上述算法的C++实现
#include <bits/stdc++.h>
using namespace std;
void nextSmallerElements(int arr[], int n) {
stack<int> s;
s.push(arr[0]);
for (int i = 1; i < n; i++) {
if (s.empty()) {
s.push(arr[i]);
continue;
}
while (!s.empty() && s.top() > arr[i]) {
cout << s.top() << " -> " << arr[i] << endl;
s.pop();
}
s.push(arr[i]);
}
while (!s.empty()) {
cout << s.top() << " -> " << -1 << endl;
s.pop();
}
}
int main() {
int arr[] = { 5, 4, 3, 2, 1 };
int n = 5;
nextSmallerElements(arr, n);
return 0;
}如果运行上面的代码,您将得到以下结果。
1 -> 2 2 -> 3 3 -> 4 4 -> 5 5 -> -1
以上就是在C++中,将以下内容翻译为中文:寻找下一个较小的元素的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号