📜  在圆形数组中查找下一个更大的元素|套装2

📅  最后修改于: 2021-05-17 21:51:25             🧑  作者: Mango

给定一个由N个整数组成的圆形数组arr [] ,任务是为圆形数组的每个元素打印“下一个更大的元素”。不存在更大元素的元素将显示“ -1”

例子:

天真的方法:本文上一篇文章讨论了解决此问题的最简单方法。

时间复杂度: O(N 2 )
辅助空间: O(N)

替代方法:有关天真方法的空间优化,请参见本文的上一篇文章。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:为了优化上述方法,其思想是使用使用堆栈数据结构的下一个更大元素的概念。请按照以下步骤解决问题:

  • 初始化堆栈以存储数组的索引和大小为N的数组nge [] ,该数组存储每个数组元素的下一个更大的元素。
  • 遍历数组,并对每个索引执行以下操作:
    • 如果堆栈为非空并且当前i数组元素大于堆栈的顶部元素,则弹出堆栈的顶部元素并通过存储arr [i%N]更新nge [st.top() ]在里面。重复此操作,直到堆栈为空或当前元素小于堆栈顶部的元素。
    • 如果堆栈为空或当前元素小于堆栈顶部,则将(i%N)推入堆栈。
  • 单次遍历N个元素之后,堆栈将包含直到第(N – 1)索引才具有下一个更大元素的元素。由于数组是圆形的,因此请再次考虑第0索引中的所有元素,并在剩余元素中找到下一个更大的元素。
  • 由于数组遍历2次,因此最好使用i%N而不是i
  • 完成上述步骤后,打印数组nge []

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the NGE for the
// given circular array arr[]
void printNGE(int* arr, int n)
{
    // Intialize stack and nge[] array
    stack s;
    int nge[n], i = 0;
 
    // Initialize nge[] array to -1
    for (i = 0; i < n; i++) {
        nge[i] = -1;
    }
    i = 0;
 
    // Traverse the array
    while (i < 2 * n) {
 
        // If stack is not empty and
        // current element is greater
        // than top element of the stack
        while (!s.empty()
               && arr[i % n] > arr[s.top()]) {
 
            // Assign next greater element
            // for the top element of the stack
            nge[s.top()] = arr[i % n];
 
            // Pop the top element
            // of the stack
            s.pop();
        }
 
        s.push(i % n);
        i++;
    }
 
    // Print the nge[] array
    for (i = 0; i < n; i++) {
        cout << nge[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 4, -2, 5, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    printNGE(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to find the NGE for the
// given circular array arr[]
static void printNGE(int arr[], int n)
{
     
    // Intialize stack and nge[] array
    Stack s = new Stack<>();
    int nge[] = new int[n];
    int i = 0;
 
    // Initialize nge[] array to -1
    for(i = 0; i < n; i++)
    {
        nge[i] = -1;
    }
    i = 0;
 
    // Traverse the array
    while (i < 2 * n)
    {
         
        // If stack is not empty and
        // current element is greater
        // than top element of the stack
        while (!s.isEmpty() &&
               arr[i % n] > arr[s.peek()])
        {
             
            // Assign next greater element
            // for the top element of the stack
            nge[s.peek()] = arr[i % n];
             
            // Pop the top element
            // of the stack
            s.pop();
        }
        s.push(i % n);
        i++;
    }
     
    // Print the nge[] array
    for(i = 0; i < n; i++)
    {
        System.out.print(nge[i] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, -2, 5, 8 };
    int N = arr.length;
 
    // Function Call
    printNGE(arr, N);
}
}
 
// This code is contributed by yashbeersingh42


Python3
# Python3 program for the above approach
 
# Function to find the NGE for the
# given circular array arr[]
def printNGE(arr, n) :
     
    # create stack list
    s = [];
     
    # Initialize nge[] array to -1
    nge = [-1] * n;
 
    i = 0;
 
    # Traverse the array
    while (i < 2 * n) :
 
        # If stack is not empty and
        # current element is greater
        # than top element of the stack
        while (len(s) != 0 and arr[i % n] > arr[s[-1]]) :
 
            # Assign next greater element
            # for the top element of the stack
            nge[s[-1]] = arr[i % n];
 
            # Pop the top element
            # of the stack
            s.pop();
 
        s.append(i % n);
        i += 1;
 
    # Print the nge[] array
    for i in range(n) :
        print(nge[i], end= " ");
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 4, -2, 5, 8 ];
    N = len(arr);
 
    # Function Call
    printNGE(arr, N);
     
    # This code is contributed by AnkitRai01


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
     
// Function to find the NGE for the
// given circular array []arr
static void printNGE(int []arr, int n)
{
     
    // Intialize stack and nge[] array
    Stack s = new Stack();
    int []nge = new int[n];
    int i = 0;
 
    // Initialize nge[] array to -1
    for(i = 0; i < n; i++)
    {
        nge[i] = -1;
    }
    i = 0;
 
    // Traverse the array
    while (i < 2 * n)
    {
         
        // If stack is not empty and
        // current element is greater
        // than top element of the stack
        while (s.Count != 0 &&
               arr[i % n] > arr[s.Peek()])
        {
             
            // Assign next greater element
            // for the top element of the stack
            nge[s.Peek()] = arr[i % n];
             
            // Pop the top element
            // of the stack
            s.Pop();
        }
        s.Push(i % n);
        i++;
    }
     
    // Print the nge[] array
    for(i = 0; i < n; i++)
    {
        Console.Write(nge[i] + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 4, -2, 5, 8 };
    int N = arr.Length;
 
    // Function Call
    printNGE(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


输出:

5 5 8 -1

时间复杂度: O(N)
辅助空间: O(N)