Encuentre todos los elementos en la array que tengan al menos dos elementos mayores

Dado un arreglo de n elementos distintos, la tarea es encontrar todos los elementos en el arreglo que tengan al menos dos elementos mayores que ellos mismos.

Ejemplos: 

Entrada: arr[] = {2, 8, 7, 1, 5};
Salida: 2 1 5  
Explicación:
Los tres elementos de salida tienen dos o más elementos mayores

Explicación:
Entrada: arr[] = {7, -2, 3, 4, 9, -1};
Salida: -2 3 4 -1  

Método 1 (simple): el enfoque ingenuo es ejecutar dos bucles y verificar uno por uno los elementos de la array para verificar que los elementos de la array tengan al menos dos elementos mayores que ellos mismos o no. Si es cierto, imprima el elemento de array. 

Implementación:

C++

// Simple C++ program to find
// all elements in array which
// have at-least two greater
// elements itself.
#include<bits/stdc++.h>
using namespace std;
 
void findElements(int arr[], int n)
{
    // Pick elements one by one and
    // count greater elements. If
    // count is more than 2, print
    // that element.
    for (int i = 0; i < n; i++)
    {
        int count = 0;
        for (int j = 0; j < n; j++)
            if (arr[j] > arr[i])
                count++;
 
        if (count >= 2)
            cout << arr[i] << " ";
    }
}
 
// Driver code
int main()
{
    int arr[] = { 2, -6 ,3 , 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    findElements(arr, n);
    return 0;
}

Java

// Java program to find all
// elements in array which
// have at-least two greater
// elements itself.
import java.util.*;
import java.io.*;
 
class GFG
{
     
static void findElements(int arr[],
                            int n)
{
    // Pick elements one by one
    // and count greater elements.
    // If count is more than 2,
    // print that element.
    for (int i = 0; i < n; i++)
    {
        int count = 0;
         
        for (int j = 0; j < n; j++)
            if (arr[j] > arr[i])
                count++;
 
        if (count >= 2)
        System.out.print(arr[i] + " ");
    }
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 2, -6 ,3 , 5, 1};
    int n = arr.length;
    findElements(arr, n);
}
}
 
// This code is contributed by Sahil_Bansall

Python3

# Python3 program to find
# all elements in array
# which have at-least two
# greater elements itself.
 
def findElements( arr, n):
 
    # Pick elements one by
        # one and count greater
    # elements. If count
        # is more than 2, print
    # that element.
 
    for i in range(n):
        count = 0
        for j in range(0, n):
            if arr[j] > arr[i]:
                count = count + 1
                         
                 
        if count >= 2 :
            print(arr[i], end=" ")
             
 
# Driver code
arr = [ 2, -6 ,3 , 5, 1]
n = len(arr)
findElements(arr, n)
     
# This code is contributed by sunnysingh

C#

// C# program to find all elements in
// array which have at least two greater
// elements itself.
using System;
 
class GFG
{
     
static void findElements(int []arr, int n)
{
    // Pick elements one by one and count
    // greater elements. If count is more
    // than 2, print that element.
    for (int i = 0; i < n; i++)
    {
        int count = 0;
         
        for (int j = 0; j < n; j++)
            if (arr[j] > arr[i])
                count++;
 
        if (count >= 2)
    Console.Write(arr[i] + " ");
    }
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = {2, -6 ,3 , 5, 1};
    int n = arr.Length;
    findElements(arr, n);
 
}
}
 
// This code is contributed by Parashar.

PHP

<?php
// Simple PHP program to find
// all elements in array which
// have at-least two greater
// elements itself.
 
function findElements($arr, $n)
{
    // Pick elements one by one and
    // count greater elements. If
    // count is more than 2,
    // print that element.
    for ($i = 0; $i < $n; $i++)
    {
        $count = 0;
        for ($j = 0; $j < $n; $j++)
            if ($arr[$j] > $arr[$i])
                $count++;
 
        if ($count >= 2)
            echo $arr[$i]." ";
    }
}
 
// Driver code
$arr = array( 2, -6 ,3 , 5, 1);
$n = sizeof($arr);
findElements($arr, $n);
 
?>

Javascript

<script>
 
// Simple Javascript program to find
// all elements in array which
// have at-least two greater
// elements itself.
 
function findElements(arr, n)
{
    // Pick elements one by one and
    // count greater elements. If
    // count is more than 2, print
    // that element.
    for (let i = 0; i < n; i++)
    {
        let count = 0;
        for (let j = 0; j < n; j++)
            if (arr[j] > arr[i])
                count++;
 
        if (count >= 2)
            document.write(arr[i] + " ");
    }
}
 
// Driver code
 
    let arr = [2, -6 ,3 , 5, 1];
    let n = arr.length;
    findElements(arr, n);
 
 
// This is code is contributed by Mayank Tyagi
 
</script>
Producción

2 -6 1 

Complejidad Temporal: O(n 2 )
Espacio Auxiliar: O(1).

Método 2 (Usar clasificación): primero ordenamos la array en orden creciente, luego imprimimos los primeros n-2 elementos donde n es el tamaño de la array. 

Implementación:

C++

// Sorting based C++ program to
// find all elements in array
// which have atleast two greater
// elements itself.
#include<bits/stdc++.h>
using namespace std;
 
void findElements(int arr[], int n)
{
    sort(arr, arr + n);
 
    for (int i = 0; i < n - 2; i++)
    cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    int arr[] = { 2, -6 ,3 , 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    findElements(arr, n);
    return 0;
}

Java

// Sorting based Java program to find
// all elements in array which have
// atleast two greater elements itself.
import java.util.*;
import java.io.*;
 
class GFG
{
 
static void findElements(int arr[], int n)
{
    Arrays.sort(arr);
 
    for (int i = 0; i < n - 2; i++)
    System.out.print(arr[i] + " ");
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 2, -6 ,3 , 5, 1};
    int n = arr.length;
    findElements(arr, n);
 
}
}
 
// This code is contributed by Sahil_Bansall

Python3

# Sorting based Python 3 program
# to find all elements in array
# which have atleast two greater
# elements itself.
 
def findElements(arr, n):
 
    arr.sort()
 
    for i in range(0, n-2):
        print(arr[i], end =" ")
 
# Driven source
arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)
 
# This code is contributed
# by Smitha Dinesh Semwal

C#

// Sorting based C# program to find
// all elements in array which have
// atleast two greater elements itself.
using System;
 
class GFG
{
 
static void findElements(int []arr, int n)
{
    Array.Sort(arr);
 
    for (int i = 0; i < n-2; i++)
        Console.Write(arr[i] + " ");
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 2, -6 ,3 , 5, 1};
    int n = arr.Length;
    findElements(arr, n);
 
}
}
 
// This code is contributed by parashar

PHP

<?php
// Sorting based PHP program to
// find all elements in array
// which have atleast two greater
// elements itself.
 
function findElements( $arr, $n)
{
    sort($arr);
 
    for ($i = 0; $i < $n - 2; $i++)
    echo $arr[$i] , " ";
}
 
// Driver Code
$arr = array( 2, -6 ,3 , 5, 1);
$n = count($arr);
findElements($arr, $n);
 
// This code is contributed by anuj_67.
?>;

Javascript

<script>
 
// Sorting based Javascript program to find 
// all elements in array which have 
// atleast two greater elements itself.
function findElements(arr, n)
{
    arr.sort();
   
    for(let i = 0; i < n - 2; i++)
        document.write(arr[i] + " ");
}
      
// Driver code   
let arr = [ 2, -6 ,3 , 5, 1];
let n = arr.length;
 
findElements(arr, n);
 
// This code is contributed by susmitakundugoaldanga 
 
</script>
Producción

-6 1 2 

Complejidad Temporal: O(n Log n)
Espacio Auxiliar: O(1).

Método 3 (Eficiente): En el segundo método, simplemente calculamos el segundo elemento máximo de la array e imprimimos todos los elementos que son menores o iguales que el segundo máximo. 

Implementación:

C++

// C++ program to find all elements
// in array which have atleast two
// greater elements itself.
#include<bits/stdc++.h>
using namespace std;
 
void findElements(int arr[], int n)
{
    int first = INT_MIN,
        second = INT_MIN;
    for (int i = 0; i < n; i++)
    {
        /* If current element is smaller
        than first then update both first
        and second */
        if (arr[i] > first)
        {
            second = first;
            first = arr[i];
        }
 
        /* If arr[i] is in between first
        and second then update second */
        else if (arr[i] > second)
            second = arr[i];
    }
 
    for (int i = 0; i < n; i++)
        if (arr[i] < second)
            cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 2, -6, 3, 5, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    findElements(arr, n);
    return 0;
}

Java

// Java program to find all elements
// in array which have atleast
// two greater elements itself.
import java.util.*;
import java.io.*;
 
class GFG
{
     
static void findElements(int arr[], int n)
{
    int first = Integer.MIN_VALUE;
    int second = Integer.MAX_VALUE;
     
    for (int i = 0; i < n; i++)
    {
        // If current element is smaller
        // than first then update both
        // first and second
        if (arr[i] > first)
        {
            second = first;
            first = arr[i];
        }
 
        /* If arr[i] is in between
        first and second
        then update second */
        else if (arr[i] > second)
            second = arr[i];
    }
 
    for (int i = 0; i < n; i++)
        if (arr[i] < second)
            System.out.print(arr[i] + " ") ;
}
// Driver code
public static void main(String args[])
{
    int arr[] = { 2, -6, 3, 5, 1};
    int n = arr.length;
    findElements(arr, n);
}
}
 
// This code is contributed by Sahil_Bansall

Python3

# Python3 program to find all elements
# in array which have atleast two
# greater elements itself.
import sys
 
def findElements(arr, n):
 
    first = -sys.maxsize
    second = -sys.maxsize
 
    for i in range(0, n):
     
        # If current element is smaller
        # than first then update both
        # first and second
        if (arr[i] > first):
         
            second = first
            first = arr[i]
         
        # If arr[i] is in between first
        # and second then update second
        elif (arr[i] > second):
            second = arr[i]
     
    for i in range(0, n):
        if (arr[i] < second):
            print(arr[i], end =" ")
 
 
# Driver code
arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)
 
# This code is contributed
# by Smitha Dinesh Semwal

C#

// C# program to find all elements
// in array which have atleast
// two greater elements itself.
using System;
 
class GFG
{
    static void findElements(int []arr,
                            int n)
    {
    int first = int.MinValue;
    int second = int.MaxValue;
     
    for (int i = 0; i < n; i++)
    {
        // If current element is smaller
        // than first then update both
        // first and second
        if (arr[i] > first)
        {
            second = first;
            first = arr[i];
        }
 
        /* If arr[i] is in between
        first and second
        then update second */
        else if (arr[i] > second)
            second = arr[i];
    }
 
    for (int i = 0; i < n; i++)
        if (arr[i] < second)
            Console.Write(arr[i] + " ") ;
}
// Driver code
public static void Main(String []args)
{
    int []arr = { 2, -6, 3, 5, 1};
    int n = arr.Length;
    findElements(arr, n);
}
}
 
// This code is contributed by parashar...

PHP

<?php
// PHP program to find all elements
// in  array which have atleast two
// greater elements itself.
 
function findElements($arr, $n)
{
     
    $first = PHP_INT_MIN;
    $second =  PHP_INT_MIN;
    for ($i = 0; $i < $n; $i++)
    {
         
            /* If current element is smaller
            than first then update both first
            and second */
            if ($arr[$i] > $first)
            {
                $second = $first;
                $first = $arr[$i];
             
     
            }
 
        /* If arr[i] is in between first
           and second then update second */
        else if ($arr[$i] > $second)
            $second = $arr[$i];
    }
 
    for($i = 0; $i < $n; $i++)
        if ($arr[$i] < $second)
            echo $arr[$i] , " ";
}
 
    // Driver code
    $arr = array(2, -6, 3, 5, 1);
    $n = count($arr);
    findElements($arr, $n);
 
// This code is contributed by vishal tripathi.
?>

Javascript

<script>
 
// Javascript program to find all elements
// in array which have atleast
// two greater elements itself.
 
function findElements(arr, n)
{
    let first = Number.MIN_VALUE;
    let second = Number.MAX_VALUE;
     
    for(let i = 0; i < n; i++)
    {
         
        // If current element is smaller
        // than first then update both
        // first and second
        if (arr[i] > first)
        {
            second = first;
            first = arr[i];
        }
         
        /* If arr[i] is in between
        first and second
        then update second */
        else if (arr[i] > second)
            second = arr[i];
    }
     
    for(let i = 0; i < n; i++)
        if (arr[i] < second)
            document.write(arr[i] + " ") ;
}
 
// Driver code
let arr = [ 2, -6, 3, 5, 1 ];
let n = arr.length;
 
findElements(arr, n);
 
// This code is contributed by divyesh072019
 
</script>
Producción

2 -6 1 

Complejidad Temporal: O(n)
Espacio Auxiliar: O(1).

Este artículo es una contribución de DANISH_RAZA . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 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 *