Home  >  Article  >  Backend Development  >  In C++, translate the following into Chinese: Find the next smaller element

In C++, translate the following into Chinese: Find the next smaller element

PHPz
PHPzforward
2023-09-20 16:29:071157browse

In C++, translate the following into Chinese: Find the next smaller element

The next smaller element is the element of the first smaller element after it. Let's look at an example.

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

The next smaller element of 5 is 4, the next smaller element of elements 1 and 2 is, 3 is - 1, because there are no smaller elements following them.

Algorithm

  • Initialize the array with random numbers

  • Initialize the stack.

  • Adds the first element to the stack.

  • Iterate through the elements of the array.

    • If the stack is empty, add the current element to the stack.

    • When the current element is smaller than the top element of the stack.

      • Print the top element and make the next smaller element the current element. p>

      • Pop up the top element.

    • #Adds an element to the stack.

  • #When the stack is not empty.

    • Print the element of the next smaller element as -1.

Implementation

Below is the C implementation of the above algorithm

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

Output

If you run the above code you will get the following results.

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

The above is the detailed content of In C++, translate the following into Chinese: Find the next smaller element. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete