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

📅  最后修改于: 2021-05-20 06:24:27             🧑  作者: Mango

给定N个整数的圆形数组arr [] ,以使给定数组的最后一个元素与数组的第一个元素相邻,任务是在此圆形数组中打印Next Greater Element。对于不存在更大元素的元素,请将下一个更大元素视为“ -1”

例子:

方法:此问题可以使用贪婪方法解决。步骤如下:

  • 为了使圆形数组的属性有效,请再次将给定的数组元素附加到同一数组。

例如:

  • 找到下一个更大的元素,直到上述数组中的N个元素形成为止。
  • 如果找到更大的元素,则打印该元素,否则打印“ -1”

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the NGE
void printNGE(int A[], int n)
{
 
    // Formation of cicular array
    int arr[2 * n];
 
    // Append the given array element twice
    for (int i = 0; i < 2 * n; i++)
        arr[i] = A[i % n];
 
    int next, i, j;
 
    // Iterate for all the
    // elements of the array
    for (i = 0; i < n; i++) {
 
        // Initialise NGE as -1
        next = -1;
 
        for (j = i + 1; j < 2 * n; j++) {
 
            // Checking for next
            // greater element
            if (arr[i] < arr[j]) {
                next = arr[j];
                break;
            }
        }
 
        // Print the updated NGE
        cout << next << ", ";
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 1 };
 
    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
static void printNGE(int []A, int n)
{
 
    // Formation of cicular array
    int []arr = new int[2 * n];
 
    // Append the given array element twice
    for(int i = 0; i < 2 * n; i++)
        arr[i] = A[i % n];
 
    int next;
 
    // Iterate for all the
    // elements of the array
    for(int i = 0; i < n; i++)
    {
 
        // Initialise NGE as -1
        next = -1;
             
        for(int j = i + 1; j < 2 * n; j++)
        {
                 
            // Checking for next
            // greater element
            if (arr[i] < arr[j])
            {
                next = arr[j];
                break;
            }
        }
             
        // Print the updated NGE
        System.out.print(next + ", ");
    }
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given array arr[]
    int []arr = { 1, 2, 1 };
 
    int N = arr.length;
 
    // Function call
    printNGE(arr, N);
}
}
 
// This code is contributed by Code_Mech


Python3
# Python3 program for the above approach
 
# Function to find the NGE
def printNGE(A, n):
 
    # Formation of cicular array
    arr = [0] * (2 * n)
 
    # Append the given array
    # element twice
    for i in range(2 * n):
        arr[i] = A[i % n]
 
    # Iterate for all the
    # elements of the array
    for i in range(n):
 
        # Initialise NGE as -1
        next = -1
 
        for j in range(i + 1, 2 * n):
 
            # Checking for next
            # greater element
            if(arr[i] < arr[j]):
                next = arr[j]
                break
 
        # Print the updated NGE
        print(next, end = ", ")
 
# Driver code
if __name__ == '__main__':
 
    # Given array arr[]
    arr = [ 1, 2, 1 ]
 
    N = len(arr)
 
    # Function call
    printNGE(arr, N)
 
# This code is contributed by Shivam Singh


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to find the NGE
static void printNGE(int []A, int n)
{
 
    // Formation of cicular array
    int []arr = new int[2 * n];
 
    // Append the given array element twice
    for(int i = 0; i < 2 * n; i++)
       arr[i] = A[i % n];
 
    int next;
 
    // Iterate for all the
    // elements of the array
    for(int i = 0; i < n; i++)
    {
 
       // Initialise NGE as -1
       next = -1;
        
       for(int j = i + 1; j < 2 * n; j++)
       {
            
          // Checking for next
          // greater element
          if (arr[i] < arr[j])
          {
              next = arr[j];
              break;
          }
       }
        
       // Print the updated NGE
       Console.Write(next + ", ");
    }
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int []arr = { 1, 2, 1 };
 
    int N = arr.Length;
 
    // Function call
    printNGE(arr, N);
}
}
 
// This code is contributed by Code_Mech


Javascript


C++
// C++ program to demonstrate the use of circular
// array without using extra memory space
 
#include 
using namespace std;
 
// Function to find the Next Greater Element(NGE)
void printNGE(int A[], int n)
{
    int k;
    for (int i = 0; i < n; i++) {
        // Initialise k as -1 which is printed when no NGE
        // found
        k = -1; //
        for (int j = i + 1; j < n + i; j++) {
            if (A[i] < A[j % n]) {
                printf("%d ", A[j % n]);
                k = 1;
                break;
            }
        }
        if (k == -1) // Gets executed when no NGE found
            printf("-1 ");
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 8, 6, 7 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printNGE(arr, N);
 
    return 0;
}


Java
// Java program to demonstrate the
// use of circular array without
// using extra memory space
import java.io.*;
 
class GFG{
     
// Function to find the Next
// Greater Element(NGE)
static void printNGE(int A[], int n)
{
    int k;
    for(int i = 0; i < n; i++)
    {
         
        // Initialise k as -1 which is
        // printed when no NGE found
        k = -1;
        for(int j = i + 1; j < n + i; j++)
        {
            if (A[i] < A[j % n])
            {
                System.out.print(A[j % n] + " ");
                k = 1;
                break;
            }
        }
         
        // Gets executed when no NGE found
        if (k == -1)
            System.out.print("-1 ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int[] arr = { 8, 6, 7 };
 
    int N = arr.length;
 
    // Function call
    printNGE(arr, N);
}
}
 
// This code is contributed by yashbeersingh42


Python3
# Python3 program to demonstrate the use of circular
# array without using extra memory space
 
# Function to find the Next Greater Element(NGE)
def printNGE(A, n) :
 
    for i in range(n) :
       
        # Initialise k as -1 which is printed when no NGE
        # found
        k = -1
        for j in range(i + 1, n + i) :
            if (A[i] < A[j % n]) :
                print(A[j % n], end = " ")
                k = 1
                break
 
        if (k == -1) : # Gets executed when no NGE found
            print("-1 ", end = "")
 
# Given array arr[]
arr = [ 8, 6, 7 ]
 
N = len(arr)
 
# Function call
printNGE(arr, N)
 
# This code is contributed by divyeshrabadia07


C#
// C# program to demonstrate the
// use of circular array without
// using extra memory space
using System;
class GFG {
     
    // Function to find the Next
    // Greater Element(NGE)
    static void printNGE(int[] A, int n)
    {
        int k;
        for(int i = 0; i < n; i++)
        {
              
            // Initialise k as -1 which is
            // printed when no NGE found
            k = -1;
            for(int j = i + 1; j < n + i; j++)
            {
                if (A[i] < A[j % n])
                {
                    Console.Write(A[j % n] + " ");
                    k = 1;
                    break;
                }
            }
              
            // Gets executed when no NGE found
            if (k == -1)
                Console.Write("-1 ");
        }
    }
   
  static void Main()
  {
     
    // Given array arr[]
    int[] arr = { 8, 6, 7 };
  
    int N = arr.Length;
  
    // Function call
    printNGE(arr, N);
  }
}
 
// This code is contributed by divyesh072019


输出
2, -1, 2,

此方法需要O(n 2 )时间,但要占用O(n)阶的额外空间

一种节省空间的解决方案是使用同一数组处理圆形数组。如果仔细观察数组,则在第n个索引之后,下一个索引始终从0开始,因此如果使用(i)%n,则使用mod运算符,我们可以轻松访问循环列表的元素并运行从第i个索引到第n + i个索引的循环,并应用mod,我们可以在给定数组内的圆形数组中进行遍历,而无需使用任何额外的空间。

下面是上述方法的实现:

C++

// C++ program to demonstrate the use of circular
// array without using extra memory space
 
#include 
using namespace std;
 
// Function to find the Next Greater Element(NGE)
void printNGE(int A[], int n)
{
    int k;
    for (int i = 0; i < n; i++) {
        // Initialise k as -1 which is printed when no NGE
        // found
        k = -1; //
        for (int j = i + 1; j < n + i; j++) {
            if (A[i] < A[j % n]) {
                printf("%d ", A[j % n]);
                k = 1;
                break;
            }
        }
        if (k == -1) // Gets executed when no NGE found
            printf("-1 ");
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 8, 6, 7 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printNGE(arr, N);
 
    return 0;
}

Java

// Java program to demonstrate the
// use of circular array without
// using extra memory space
import java.io.*;
 
class GFG{
     
// Function to find the Next
// Greater Element(NGE)
static void printNGE(int A[], int n)
{
    int k;
    for(int i = 0; i < n; i++)
    {
         
        // Initialise k as -1 which is
        // printed when no NGE found
        k = -1;
        for(int j = i + 1; j < n + i; j++)
        {
            if (A[i] < A[j % n])
            {
                System.out.print(A[j % n] + " ");
                k = 1;
                break;
            }
        }
         
        // Gets executed when no NGE found
        if (k == -1)
            System.out.print("-1 ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int[] arr = { 8, 6, 7 };
 
    int N = arr.length;
 
    // Function call
    printNGE(arr, N);
}
}
 
// This code is contributed by yashbeersingh42

Python3

# Python3 program to demonstrate the use of circular
# array without using extra memory space
 
# Function to find the Next Greater Element(NGE)
def printNGE(A, n) :
 
    for i in range(n) :
       
        # Initialise k as -1 which is printed when no NGE
        # found
        k = -1
        for j in range(i + 1, n + i) :
            if (A[i] < A[j % n]) :
                print(A[j % n], end = " ")
                k = 1
                break
 
        if (k == -1) : # Gets executed when no NGE found
            print("-1 ", end = "")
 
# Given array arr[]
arr = [ 8, 6, 7 ]
 
N = len(arr)
 
# Function call
printNGE(arr, N)
 
# This code is contributed by divyeshrabadia07

C#

// C# program to demonstrate the
// use of circular array without
// using extra memory space
using System;
class GFG {
     
    // Function to find the Next
    // Greater Element(NGE)
    static void printNGE(int[] A, int n)
    {
        int k;
        for(int i = 0; i < n; i++)
        {
              
            // Initialise k as -1 which is
            // printed when no NGE found
            k = -1;
            for(int j = i + 1; j < n + i; j++)
            {
                if (A[i] < A[j % n])
                {
                    Console.Write(A[j % n] + " ");
                    k = 1;
                    break;
                }
            }
              
            // Gets executed when no NGE found
            if (k == -1)
                Console.Write("-1 ");
        }
    }
   
  static void Main()
  {
     
    // Given array arr[]
    int[] arr = { 8, 6, 7 };
  
    int N = arr.Length;
  
    // Function call
    printNGE(arr, N);
  }
}
 
// This code is contributed by divyesh072019

输出
-1 7 8

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

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。