C++ 中的下一个较小元素


下一个较小元素是元素之后出现的第一个较小元素。我们来看一个例子。

arr = [1, 2, 3, 5, 4]

5 的下一个较小元素是 4,而元素 1、2、3 的下一个较小元素为 -1,因为它们之后没有更小的元素。

算法

  • 使用随机数初始化数组

  • 初始化一个堆栈。

  • 将第一个元素添加到堆栈中。

  • 遍历数组元素。

    • 如果堆栈为空,则将当前元素添加到堆栈中。

    • 当当前元素小于堆栈顶元素时。

      • 打印堆栈顶元素,并将下一个较小元素作为当前元素。

      • 弹出堆栈顶元素。

    • 将元素添加到堆栈中。

  • 当堆栈不为空时。

    • 打印元素,下一个较小元素为 -1。

实现

以下是上述算法在 C++ 中的实现

Open Compiler
#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; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

如果你运行上述代码,那么你会得到以下结果。

1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> -1

更新于:2021 年 10 月 25 日

1K+ 浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告