Encuentra el segundo elemento más grande en una array

Dado un arreglo de enteros, nuestra tarea es escribir un programa que encuentre eficientemente el segundo elemento más grande presente en el arreglo. 

Ejemplo:

Input: arr[] = {12, 35, 1, 10, 34, 1}
Output: The second largest element is 34.
Explanation: The largest element of the 
array is 35 and the second 
largest element is 34

Input: arr[] = {10, 5, 10}
Output: The second largest element is 5.
Explanation: The largest element of 
the array is 10 and the second 
largest element is 5

Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array 
is 10 there is no second largest element

Complete Interview Preparation - GFG

Solución simple

Enfoque: la idea es ordenar la array en orden descendente y luego devolver el segundo elemento que no es igual al elemento más grande de la array ordenada.

Implementación:

C++

// C++ program to find second largest element in an array
 
#include <bits/stdc++.h>
using namespace std;
 
/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
    int i, first, second;
    /* There should be atleast two elements */
    if (arr_size < 2) {
        printf(" Invalid Input ");
        return;
    }
    // sort the array
    sort(arr, arr + arr_size);
    // start from second last element as the largest element
    // is at last
    for (i = arr_size - 2; i >= 0; i--) {
        // if the element is not equal to largest element
        if (arr[i] != arr[arr_size - 1]) {
            printf("The second largest element is %d\n",arr[i]);
            return;
        }
    }
    printf("There is no second largest element\n");
}
 
/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2largest(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C

// C program to find second largest element in an array
#include <stdio.h>
#include<stdlib.h>
 
// Compare function for qsort
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}
 
/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
    int i, first, second;
    /* There should be atleast two elements */
    if (arr_size < 2) {
        printf(" Invalid Input ");
        return;
    }
    // sort the array
    qsort(arr, arr_size, sizeof(int), cmpfunc);
    // start from second last element as the largest element
    // is at last
    for (i = arr_size - 2; i >= 0; i--) {
        // if the element is not
        // equal to largest element
        if (arr[i] != arr[arr_size - 1]) {
            printf("The second largest element is %d\n",arr[i]);
            return;
        }
    }
    printf("There is no second largest element\n");
}
 
/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2largest(arr, n);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java

// Java program to find second largest
// element in an array
import java.util.*;
class GFG{
 
// Function to print the
// second largest elements
static void print2largest(int arr[],
                          int arr_size)
{
  int i, first, second;
 
  // There should be
  // atleast two elements
  if (arr_size < 2)
  {
    System.out.printf(" Invalid Input ");
    return;
  }
 
  // Sort the array
  Arrays.sort(arr);
 
  // Start from second last element
  // as the largest element is at last
  for (i = arr_size - 2; i >= 0; i--)
  {
    // If the element is not
    // equal to largest element
    if (arr[i] != arr[arr_size - 1])
    {
      System.out.printf("The second largest " +
                        "element is %d\n", arr[i]);
      return;
    }
  }
 
  System.out.printf("There is no second " +
                    "largest element\n");
}
 
// Driver code
public static void main(String[] args)
{
  int arr[] = {12, 35, 1, 10, 34, 1};
  int n = arr.length;
  print2largest(arr, n);
}
}
 
// This code is contributed by gauravrajput1

Python3

# Python3 program to find second
# largest element in an array
 
# Function to print the
# second largest elements
def print2largest(arr,
                  arr_size):
  
  # There should be
  # atleast two elements
  if (arr_size < 2):  
    print(" Invalid Input ")
    return
  
  # Sort the array
  arr.sort
  
  # Start from second last
  # element as the largest
  # element is at last
  for i in range(arr_size-2,
                 -1, -1):
  
    # If the element is not
    # equal to largest element
    if (arr[i] != arr[arr_size - 1]) :
     
      print("The second largest element is",
            arr[i])
      return
  
  print("There is no second largest element")
 
# Driver code
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)
 
# This code is contributed by divyeshrabadiya07

C#

// C# program to find second largest
// element in an array
using System;
 
class GFG{
 
// Function to print the
// second largest elements
static void print2largest(int []arr,
                          int arr_size)
{
  int i;
 
  // There should be
  // atleast two elements
  if (arr_size < 2)
  {
    Console.Write(" Invalid Input ");
    return;
  }
 
  // Sort the array
  Array.Sort(arr);
 
  // Start from second last element
  // as the largest element is at last
  for(i = arr_size - 2; i >= 0; i--)
  {
       
    // If the element is not
    // equal to largest element
    if (arr[i] != arr[arr_size - 1])
    {
      Console.Write("The second largest " +
                    "element is {0}\n", arr[i]);
      return;
    }
  }
 
  Console.Write("There is no second " +
                "largest element\n");
}
 
// Driver code
public static void Main(String[] args)
{
  int []arr = { 12, 35, 1, 10, 34, 1 };
  int n = arr.Length;
   
  print2largest(arr, n);
}
}
 
// This code is contributed by Amit Katiyar

Javascript

<script>
 
// Javascript program to find second largest
// element in an array
  
    // Function to print the second largest elements
    function print2largest(arr, arr_size) {
        let i, first, second;
  
        // There should be atleast two elements
        if (arr_size < 2) {
            document.write(" Invalid Input ");
            return;
        }
  
        // sort the array
        arr.sort();
  
        // start from second last element
        // as the largest element is at last
        for (i = arr_size - 2; i >= 0; i--) {
            // if the element is not
            // equal to largest element
            if (arr[i] != arr[arr_size - 1]) {
                document.write("The second largest element is " + arr[i]);
                return;
            }
        }
  
        document.write("There is no second largest element<br>");
    }
  
    // Driver program to test above function
 
    let arr= [ 12, 35, 1, 10, 34, 1 ];
    let n = arr.length;
    print2largest(arr, n);
 
     
// This code is contributed by Surbhi Tyagi
 
</script>
Producción

The second largest element is 34

Análisis de Complejidad:

  • Complejidad temporal: O(n log n). 
    El tiempo requerido para ordenar la array es O(n log n).
  • Espacio auxiliar: O(1). 
    Como no se requiere espacio adicional.

Mejor solución: 

Enfoque: El enfoque es atravesar la array dos veces. 

En el primer recorrido encuentre el elemento máximo. 

En el segundo recorrido encuentre el elemento mayor en el resto excluyendo el anterior mayor.

Implementación:

C++14

// C++ program to find the second largest element in the array
#include <iostream>
using namespace std;
 
 
int secondLargest(int arr[], int n) {
    int largest = 0, secondLargest = -1;
 
    // finding the largest element in the array
    for (int i = 1; i < n; i++) {
        if (arr[i] > arr[largest])
            largest = i;
    }
 
    // finding the largest element in the array excluding
    // the largest element calculated above
    for (int i = 0; i < n; i++) {
        if (arr[i] != arr[largest]) {
            // first change the value of second largest
            // as soon as the next element is found
            if (secondLargest == -1)
                secondLargest = i;
            else if (arr[i] > arr[secondLargest])
                secondLargest = i;
        }
    }
    return secondLargest;
}
 
 
int main() {
    int arr[] = {10, 12, 20, 4};
    int n = sizeof(arr)/sizeof(arr[0]);
    int second_Largest = secondLargest(arr, n);
    if (second_Largest == -1)
        cout << "Second largest didn't exit\n";
    else
        cout << "Second largest : " << arr[second_Largest];
}

Java

// Java program to find second largest
// element in an array
class GFG{
 
// Function to print the second largest elements
static void print2largest(int arr[], int arr_size)
{
    int i, first, second;
 
    // There should be atleast two elements
    if (arr_size < 2)
    {
        System.out.printf(" Invalid Input ");
        return;
    }
 
    int largest = second = Integer.MIN_VALUE;
 
    // Find the largest element
    for(i = 0; i < arr_size; i++)
    {
        largest = Math.max(largest, arr[i]);
    }
 
    // Find the second largest element
    for(i = 0; i < arr_size; i++)
    {
        if (arr[i] != largest)
            second = Math.max(second, arr[i]);
    }
    if (second == Integer.MIN_VALUE)
        System.out.printf("There is no second " +
                          "largest element\n");
    else
        System.out.printf("The second largest " +
                          "element is %d\n", second);
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = arr.length;
     
    print2largest(arr, n);
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python3 program to find
# second largest element
# in an array
 
# Function to print
# second largest elements
def print2largest(arr, arr_size):
 
    # There should be atleast
    # two elements
    if (arr_size < 2):
        print(" Invalid Input ");
        return;
 
    largest = second = -2454635434;
 
    # Find the largest element
    for i in range(0, arr_size):
        largest = max(largest, arr[i]);
 
    # Find the second largest element
    for i in range(0, arr_size):
        if (arr[i] != largest):
            second = max(second, arr[i]);
 
    if (second == -2454635434):
        print("There is no second " +
              "largest element");
    else:
        print("The second largest " +
              "element is \n", second);
 
# Driver code
if __name__ == '__main__':
   
    arr = [12, 35, 1,
           10, 34, 1];
    n = len(arr);
    print2largest(arr, n);
 
# This code is contributed by shikhasingrajput

C#

// C# program to find second largest
// element in an array
using System;
 
class GFG{
 
// Function to print the second largest elements
static void print2largest(int []arr, int arr_size)
{
    // int first;
    int i, second;
 
    // There should be atleast two elements
    if (arr_size < 2)
    {
        Console.Write(" Invalid Input ");
        return;
    }
 
    int largest = second = int.MinValue;
 
    // Find the largest element
    for(i = 0; i < arr_size; i++)
    {
        largest = Math.Max(largest, arr[i]);
    }
 
    // Find the second largest element
    for(i = 0; i < arr_size; i++)
    {
        if (arr[i] != largest)
            second = Math.Max(second, arr[i]);
    }
     
    if (second == int.MinValue)
        Console.Write("There is no second " +
                      "largest element\n");
    else
        Console.Write("The second largest " +
                      "element is {0}\n", second);
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 12, 35, 1, 10, 34, 1 };
    int n = arr.Length;
     
    print2largest(arr, n);
}
}
 
// This code is contributed by Amit Katiyar

Javascript

<script>
  
// Javascript program to find second largest
// element in an array
   
    // Function to print the second largest elements
    function print2largest(arr, arr_size) {
        let i;
        let largest = second = -2454635434;
   
        // There should be atleast two elements
        if (arr_size < 2) {
            document.write(" Invalid Input ");
            return;
        }
   
        // finding the largest element
        for (i = 0;i<arr_size;i++){
            if (arr[i]>largest){
                largest = arr[i];
            }
        }
   
        // Now find the second largest element
        for (i = 0 ;i<arr_size;i++){
            if (arr[i]>second && arr[i]<largest){
                second = arr[i];
            }
        }
  
        if (second == -2454635434){
             
        document.write("There is no second largest element<br>");
        }
        else{
            document.write("The second largest element is " + second);
                return;
            }
        }
     
   
    // Driver program to test above function
  
    let arr= [ 12, 35, 1, 10, 34, 1 ];
    let n = arr.length;
    print2largest(arr, n);
   
</script>
Producción

Second largest : 12

Análisis de Complejidad:

  • Complejidad temporal: O(n). 
    Se necesitan dos recorridos de la array.
  • Espacio auxiliar: O(1). 
    Como no se requiere espacio adicional.

Solución eficiente:

Enfoque: Encuentre el segundo elemento más grande en un solo recorrido. 
A continuación se muestra el algoritmo completo para hacer esto:  

1) Initialize the first as 0(i.e, index of arr[0] element
2) Start traversing the array from array[1],
   a) If the current element in array say arr[i] is greater
      than first. Then update first and second as,
      second = first
      first = arr[i]
   b) If the current element is in between first and second,
      then update second to store the value of current variable as
      second = arr[i]
3) Return the value stored in second.

Implementación:

C

// C program to find second largest
// element in an array
 
#include <limits.h>
#include <stdio.h>
 
/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
    int i, first, second;
 
    /* There should be atleast two elements */
    if (arr_size < 2) {
        printf(" Invalid Input ");
        return;
    }
 
    first = second = INT_MIN;
    for (i = 0; i < arr_size; i++) {
        /* If current element is greater 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 && arr[i] != first)
            second = arr[i];
    }
    if (second == INT_MIN)
        printf("There is no second largest element\n");
    else
        printf("The second largest element is %d", second);
}
 
/* Driver program to test above function */
int main()
{
    int arr[] = { 12, 35, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2largest(arr, n);
    return 0;
}

C++

// C++ program to find the second largest element
 
#include <iostream>
using namespace std;
 
// returns the index of second largest
// if second largest didn't exist return -1
int secondLargest(int arr[], int n) {
    int first = 0, second = -1;
    for (int i = 1; i < n; i++) {
        if (arr[i] > arr[first]) {
            second = first;
            first = i;
        }
        else if (arr[i] < arr[first]) {
            if (second == -1 || arr[second] < arr[i])
                second = i;
        }
    }
    return second;
}
 
int main() {
    int arr[] = {10, 12, 20, 4};
    int index = secondLargest(arr, sizeof(arr)/sizeof(arr[0]));
    if (index == -1)
        cout << "Second Largest didn't exist";
    else
        cout << "Second largest : " << arr[index];
}

Java

// JAVA Code for Find Second largest
// element in an array
class GFG {
 
    /* Function to print the second largest
    elements */
    public static void print2largest(int arr[],
                                     int arr_size)
    {
        int i, first, second;
 
        /* There should be atleast two elements */
        if (arr_size < 2) {
            System.out.print(" Invalid Input ");
            return;
        }
 
        first = second = Integer.MIN_VALUE;
        for (i = 0; i < arr_size; i++) {
            /* If current element is greater 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 && arr[i] != first)
                second = arr[i];
        }
 
        if (second == Integer.MIN_VALUE)
            System.out.print("There is no second largest"
                             + " element\n");
        else
            System.out.print("The second largest element"
                             + " is " + second);
    }
 
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = { 12, 35, 1, 10, 34, 1 };
        int n = arr.length;
        print2largest(arr, n);
    }
}
// This code is contributed by Arnav Kr. Mandal.

Python3

# Python program to
# find second largest
# element in an array
 
 
# Function to print the
# second largest elements
def print2largest(arr, arr_size):
 
    # There should be atleast
        # two elements
    if (arr_size < 2):
     
        print(" Invalid Input ")
        return
     
 
    first = second = -2147483648
    for i in range(arr_size):
     
        # 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 and arr[i] != first):
            second = arr[i]
     
    if (second == -2147483648):
        print("There is no second largest element")
    else:
        print("The second largest element is", second)
 
 
# Driver program to test
# above function
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
 
print2largest(arr, n)
 
# This code is contributed
# by Anant Agarwal.

C#

// C# Code for Find Second largest
// element in an array
using System;
 
class GFG {
 
    // Function to print the
    // second largest elements
    public static void print2largest(int[] arr,
                                     int arr_size)
    {
        int i, first, second;
 
        // There should be atleast two elements
        if (arr_size < 2) {
            Console.WriteLine(" Invalid Input ");
            return;
        }
 
        first = second = int.MinValue;
        for (i = 0; i < arr_size; 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 && arr[i] != first)
                second = arr[i];
        }
 
        if (second == int.MinValue)
            Console.Write("There is no second largest"
                          + " element\n");
        else
            Console.Write("The second largest element"
                          + " is " + second);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 12, 35, 1, 10, 34, 1 };
        int n = arr.Length;
        print2largest(arr, n);
    }
}
 
// This code is contributed by Parashar.

PHP

<?php
// PHP program to find second largest
// element in an array
 
// Function to print the
// second largest elements
function print2largest($arr, $arr_size)
{
 
    // There should be atleast
    // two elements
    if ($arr_size < 2)
    {
        echo(" Invalid Input ");
        return;
    }
 
    $first = $second = PHP_INT_MIN;
    for ($i = 0; $i < $arr_size ; $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 &&
                 $arr[$i] != $first)
            $second = $arr[$i];
    }
    if ($second == PHP_INT_MIN)
        echo("There is no second largest element\n");
    else
        echo("The second largest element is " . $second . "\n");
}
 
// Driver Code
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
print2largest($arr, $n);
 
// This code is contributed by Ajit.
?>

Javascript

<script>
  
// Javascript program to find second largest
// element in an array
   
    // Function to print the second largest elements
    function print2largest(arr, arr_size) {
        let i;
        let largest = second = -2454635434;
   
        // There should be atleast two elements
        if (arr_size < 2) {
            document.write(" Invalid Input ");
            return;
        }
   
        // finding the largest element
         
        for (i = 0 ;i<arr_size;i++){
            if (arr[i]>largest){
                second = largest ;
                largest = arr[i]
            }
 
            else if (arr[i]!=largest && arr[i]>second ){
                second = arr[i];
            }
        }
  
        if (second == -2454635434){
             
        document.write("There is no second largest element<br>");
        }
        else{
            document.write("The second largest element is " + second);
                return;
            }
        }
     
 
    // Driver program to test above function
  
    let arr= [ 12, 35, 1, 10, 34, 1 ];
    let n = arr.length;
    print2largest(arr, n);
     
 // This code is contributed by Shaswat Singh
  
</script>
Producción

The second largest element is 34

Análisis de Complejidad:

  • Complejidad temporal: O(n). 
    Solo se necesita un recorrido de la array.
  • Espacio auxiliar: O(1). 
    Como no se requiere espacio adicional.

Artículo relacionado
el elemento más pequeño y el segundo más pequeño de una array

Este artículo es una contribución de Harsh Agarwal . 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 *