Elementos mayores más pequeños en toda la array

Se da una array de longitud n, y necesitamos calcular el siguiente elemento mayor para cada elemento de la array dada. Si el siguiente elemento mayor no está disponible en la array dada, entonces debemos completar ‘_’ en ese lugar de índice.

Ejemplos: 

Input :  6 3 9 8 10 2 1 15 7 
Output : 7 6 10 9 15 3 2 _ 8
Here every element of array has next greater 
element but at index 7,
15 is the greatest element of given array
and no other element is greater from 15 
so at the index of 15 we fill with '_' .

Input  : 13 6 7 12
Output : _ 7 12 13
Here, at index 0, 13 is the greatest 
value in given array and no other 
array element is greater from 13 so
at index 0 we fill '_'.

Preguntado en : Zoho 

Una solución simple es usar dos bucles anidados. El ciclo externo selecciona todos los elementos uno por uno y el ciclo interno encuentra el siguiente elemento mayor mediante una búsqueda lineal de principio a fin. 

C++

// Simple C++ program to find smallest greater element in
// whole array for every element.
#include <bits/stdc++.h>
using namespace std;
 
void smallestGreater(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
 
        // Find the closest greater element for arr[j] in
        // the entire array.
        int diff = INT_MAX, closest = -1;
        for (int j = 0; j < n; j++) {
            if (arr[i] < arr[j] && arr[j] - arr[i] < diff) {
                diff = arr[j] - arr[i];
                closest = j;
            }
        }
 
        // Check if arr[i] is largest
        (closest == -1) ? cout << "_ "
                        : cout << arr[closest] << " ";
    }
}
 
// Driver code
int main()
{
    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };
    int n = sizeof(ar) / sizeof(ar[0]);
    smallestGreater(ar, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C

// Simple C program to find smallest greater element in
// whole array for every element.
#include <stdio.h>
#include <limits.h>
 
void smallestGreater(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
 
        // Find the closest greater element for arr[j] in
        // the entire array.
        int diff = INT_MAX, closest = -1;
        for (int j = 0; j < n; j++) {
            if (arr[i] < arr[j] && arr[j] - arr[i] < diff) {
                diff = arr[j] - arr[i];
                closest = j;
            }
        }
 
        // Check if arr[i] is largest
        (closest == -1) ? printf("_ ")
                        : printf("%d ",arr[closest]);
    }
}
 
// Driver code
int main()
{
    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };
    int n = sizeof(ar) / sizeof(ar[0]);
    smallestGreater(ar, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java

// Simple Java program to find smallest greater element in
// whole array for every element.
import java.io.*;
 
class GFG {
    static void smallestGreater(int arr[], int n)
    {
        for (int i = 0; i < n; i++) {
            // Find the closest greater element for arr[j]
            // in  the entire array.
            int diff = Integer.MAX_VALUE;
            int closest = -1;
            for (int j = 0; j < n; j++) {
                if (arr[i] < arr[j] && arr[j] - arr[i] < diff) {
                    diff = arr[j] - arr[i];
                    closest = j;
                }
            }
 
            // Check if arr[i] is largest
            if (closest == -1)
                System.out.print("_ ");
            else
                System.out.print(arr[closest] + " ");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };
        int n = ar.length;
        smallestGreater(ar, n);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Python3

# Simple Python3 program to find smallest
# greater element in whole array for
# every element.
def smallestGreater(arr, n) :
    for i in range(0, n) :
 
        # Find the closest greater element
        # for arr[j] in the entire array.
        diff = 1000;
        closest = -1;
        for j in range(0, n) :
            if ( arr[i] < arr[j] and
                  arr[j] - arr[i] < diff) :
                diff = arr[j] - arr[i];
                closest = j;    
         
        # Check if arr[i] is largest
        if (closest == -1) :
            print ("_ ", end = "");
        else :
            print ("{} ".format(arr[closest]),
                                    end = "");
 
# Driver code
ar = [6, 3, 9, 8, 10, 2, 1, 15, 7];
n = len(ar) ;
smallestGreater(ar, n);
 
# This code is contributed by Manish Shaw
# (manishshaw1)

C#

// Simple C# program to find
// smallest greater element in
// whole array for every element.
using System;
 
class GFG
{
static void smallestGreater(int []arr,
                            int n)
{
    for (int i = 0; i < n; i++)
    {
 
        // Find the closest greater
        // element for arr[j] in
        // the entire array.
        int diff = int.MaxValue;
        int closest = -1;
        for (int j = 0; j < n; j++)
        {
            if (arr[i] < arr[j] &&
                arr[j] - arr[i] < diff)
            {
                diff = arr[j] - arr[i];
                closest = j;        
            }
        }
         
        // Check if arr[i] is largest
        if(closest == -1)
        Console.Write( "_ " );
        else
        Console.Write(arr[closest] + " ");
    }
}
 
// Driver code
public static void Main()
{
    int []ar = {6, 3, 9, 8, 10,
                2, 1, 15, 7};
    int n = ar.Length;
    smallestGreater(ar, n);
}
}
 
// This code is contributed by anuj_67.

PHP

<?php
// Simple PHP program to find smallest
// greater element in whole array for
// every element.
 
function smallestGreater($arr, $n)
{
    for ( $i = 0; $i < $n; $i++) {
 
        // Find the closest greater element
        // for arr[j] in the entire array.
        $diff = PHP_INT_MAX; $closest = -1;
        for ( $j = 0; $j < $n; $j++) {
            if ( $arr[$i] < $arr[$j] &&
                $arr[$j] - $arr[$i] < $diff)
            {
                $diff = $arr[$j] - $arr[$i];
                $closest = $j;    
            }
        }
         
        // Check if arr[i] is largest
        if ($closest == -1)
        echo "_ " ;
        else
            echo $arr[$closest] , " ";
    }
}
 
    // Driver code
    $ar = array (6, 3, 9, 8, 10, 2, 1, 15, 7);
    $n = sizeof($ar) ;
    smallestGreater($ar, $n);
 
// This code is contributed by ajit
?>

Javascript

<script>
 
    // Simple Javascript program to find
    // smallest greater element in
    // whole array for every element.
     
    function smallestGreater(arr, n)
    {
        for (let i = 0; i < n; i++)
        {
 
            // Find the closest greater
            // element for arr[j] in
            // the entire array.
            let diff = Number.MAX_VALUE;
            let closest = -1;
            for (let j = 0; j < n; j++)
            {
                if (arr[i] < arr[j] &&
                    arr[j] - arr[i] < diff)
                {
                    diff = arr[j] - arr[i];
                    closest = j;       
                }
            }
 
            // Check if arr[i] is largest
            if(closest == -1)
                document.write( "_ " );
            else
                document.write(arr[closest] + " ");
        }
    }
     
    let ar = [6, 3, 9, 8, 10, 2, 1, 15, 7];
    let n = ar.length;
    smallestGreater(ar, n);
     
</script>
Producción: 

7 6 10 9 15 3 2 _ 8

 

Complejidad temporal: O(n*n) 
Espacio auxiliar: O(1)

Una solución eficiente es insertar elementos uno por uno en un conjunto (un árbol de búsqueda binario autoequilibrado). Después de insertarlo en el conjunto, buscamos elementos. Después de encontrar el iterador del elemento buscado, movemos el iterador al siguiente (tenga en cuenta que el conjunto almacena los elementos en orden) para encontrar un elemento que sea simplemente mayor.

C++

// Efficient C++ program to find smallest
// greater element in whole array for
// every element.
#include <bits/stdc++.h>
using namespace std;
 
void smallestGreater(int arr[], int n)
{
    set<int> s;
    for (int i = 0; i < n; i++)
       s.insert(arr[i]);
 
    for (int i = 0; i < n; i++)
    {
       auto it = s.find(arr[i]);
       it++;
       if (it != s.end())          
          cout << *it << " ";      
       else
          cout << "_ ";
     }
}
 
// Driver code
int main()
{
    int ar[] = { 6, 3, 9, 8, 10, 2, 1, 15, 7 };
    int n = sizeof(ar) / sizeof(ar[0]);
    smallestGreater(ar, n);
    return 0;
}

Java

// Efficient Java program to
// find smallest greater element
// in whole array for every element.
import java.util.*;
class GFG{
 
static void smallestGreater(int arr[],
                            int n)
{
  HashSet<Integer> s = new HashSet<>();
  for (int i = 0; i < n; i++)
    s.add(arr[i]);
  Vector<Integer> newAr = new Vector<>();
  for (int p : s)
  {
    newAr.add(p);
  }
 
  for (int i = 0; i < n; i++)
  {
    int temp = lowerBound(newAr, 0,
                          newAr.size(),
                          arr[i]);
    if (temp  < n)
      System.out.print(newAr.get(temp) + " ");
    else
      System.out.print("_ ");
  }
}
 
static int lowerBound(Vector<Integer> vec,
                      int low, int high,
                      int element)
{
  int[] array = new int[vec.size()];
  int k = 0;
  for (Integer val : vec)
  {
    array[k] = val;
    k++;
  }
   
  // vec.clear();
  while (low < high)
  {
    int middle = low +
                 (high - low) / 2;
    if (element > array[middle])
    {
      low = middle + 1;
    } else
    {
      high = middle;
    }
  }
 
  return low+1;
}
 
// Driver code
public static void main(String[] args)
{
  int ar[] = {6, 3, 9, 8,
              10, 2, 1, 15, 7};
  int n = ar.length;
  smallestGreater(ar, n);
}
}
 
// This code is contributed by gauravrajput1

Python3

# Efficient Python3 program to
# find smallest greater element
# in whole array for every element
def smallestGreater(arr, n):
     
    s = set()
     
    for i in range(n):
        s.add(arr[i])
         
    newAr = []
     
    for p in s:
        newAr.append(p)
 
    for i in range(n):
        temp = lowerBound(newAr, 0, len(newAr),
                          arr[i])
                           
        if (temp < n):
            print(newAr[temp], end = " ")
        else:
            print("_ ", end = "")
 
def lowerBound(vec, low, high, element):
     
    array = [0] * (len(vec))
     
    k = 0
     
    for val in vec:
        array[k] = val
        k += 1
         
    # vec.clear();
    while (low < high):
        middle = low + int((high - low) / 2)
         
        if (element > array[middle]):
            low = middle + 1
        else:
            high = middle
 
    return low + 1
 
# Driver code
if __name__ == '__main__':
     
    ar = [ 6, 3, 9, 8, 10, 2, 1, 15, 7 ]
    n = len(ar)
     
    smallestGreater(ar, n)
 
# This code is contributed by shikhasingrajput

C#

// Efficient C# program to
// find smallest greater element
// in whole array for every element.
using System;
using System.Collections.Generic;
class GFG{
 
static void smallestGreater(int[] arr,
                                int n)
{
  HashSet<int> s = new HashSet<int>();
  for (int i = 0; i < n; i++)
  {
    s.Add(arr[i]);
  }
   
  int[] newAr = new int[s.Count];
  int j = 0;
  foreach(int p in s)
  {
    newAr[j] = p;
    j++;
  }
   
  Array.Sort(newAr);
   
  for (int i = 0; i < n; i++)
  {
    int temp = lowerBound(newAr, 0,
                          newAr.GetLength(0),
                          arr[i]);
    if (temp < n)
      Console.Write(newAr[temp] + " ");
    else
      Console.Write("_ ");
  }
}
 
static int lowerBound(int[] array, int low,
                      int high, int element)
{
  while (low < high)
  {
    int middle = low + (high -
                 low) / 2;
     
    if (element > array[middle])
    {
      low = middle + 1;
    }
    else
    {
      high = middle;
    }
  }
  return low + 1;
}
 
// Driver code
public static void Main(String[] args)
{
  int[] ar = {6, 3, 9, 8,
              10, 2, 1, 15, 7};
  int n = ar.Length;
  smallestGreater(ar, n);
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
// Efficient Javascript program to
// find smallest greater element
// in whole array for every element.
 
function smallestGreater(arr,n)
{
     let s = new Set();
  for (let i = 0; i < n; i++)
    s.add(arr[i]);
  let newAr = [];
  for (let p of s.values())
  {
    newAr.push(p);
  }
     newAr.sort(function(a,b){return a-b;});
     
  for (let i = 0; i < n; i++)
  {
       
    let temp = lowerBound(newAr, 0,
                          newAr.length,
                          arr[i]);
     
    if(temp  < n)
      document.write(newAr[temp] + " ");
    else
      document.write("_ ");
  }
}
 
function lowerBound(vec,low,high,element)
{
    let array = [...vec];
   
    
  // vec.clear();
  while (low < high)
  {
    let middle = Math.floor(low +
                 (high - low) / 2);
    if (element > array[middle])
    {
      low = middle + 1;
    }
    else
    {
      high = middle;
    }
  }
  
  return low+1;
}
 
// Driver code
let ar=[6, 3, 9, 8,
              10, 2, 1, 15, 7];
let n = ar.length;
smallestGreater(ar, n);
 
// This code is contributed by patel2127
</script>
Producción : 

7 6 10 9 15 3 2 _ 8

 

Complejidad Temporal: O(n Log n). Tenga en cuenta que las operaciones de inserción del árbol de búsqueda autoequilibrado (implementado por set en C++) tardan O(Log n) en insertarse y buscarse. 
Espacio Auxiliar: O(n)

También podemos usar la ordenación seguida de búsquedas binarias para resolver el problema anterior al mismo tiempo y en el mismo espacio auxiliar.

Publicación traducida automáticamente

Artículo escrito por aditya1011 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *