Imprime la última aparición de elementos en la array en orden relativo

Dada una array de N elementos, imprima los elementos en el mismo orden relativo dado eliminando todas las ocurrencias de elementos excepto la última ocurrencia. 
Ejemplos
 

Entrada: a[] = {1, 5, 5, 1, 6, 1} 
Salida: 5 6 1 
Elimina dos enteros 1, que están en las posiciones 1 y 4. Además, elimina el entero 5, que está en la posición 2. 
Por lo tanto, la array de la izquierda es {5, 6, 1}
Entrada: a[] = {2, 5, 5, 2} 
Salida: 5 2 
 

Acercarse: 
 

  • Hash la última aparición de cada elemento.
  • Itere en la array de N elementos, si el índice del elemento tiene hash, luego imprima el elemento de la array.

A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ program to print the last occurrence
// of every element in relative order
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the last occurrence
// of every element in an array
void printLastOccurrence(int a[], int n)
{
 
    // used in hashing
    unordered_map<int, int> mp;
 
    // iterate and store the last index
    // of every element
    for (int i = 0; i < n; i++)
        mp[a[i]] = i;
 
    // iterate and check for the last
    // occurrence of every element
    for (int i = 0; i < n; i++) {
        if (mp[a[i]] == i)
            cout << a[i] << " ";
    }
}
// Driver Code
int main()
{
    int a[] = { 1, 5, 5, 1, 6, 1 };
    int n = sizeof(a) / sizeof(a[0]);
    printLastOccurrence(a, n);
 
    return 0;
}

Java

// Java program to print the
// last occurrence of every
// element in relative order
import java.util.*;
 
class GFG
{
     
    // Function to print the last
    // occurrence of every element
    // in an array
    public static void printLastOccurrence(int a[],
                                           int n)
    {
        HashMap<Integer,
                Integer> map = new HashMap<Integer,
                                           Integer>();
         
        // iterate and store the last
        // index of every element
        for (int i = 0; i < n; i++)
            map.put(a[i], i);
             
        for (int i = 0; i < n; i++)
        {
        if (map.get(a[i]) == i)
            System.out.print(a[i] +" ");
        }
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int a[] = { 1, 5, 5, 1, 6, 1 };
        int n = a.length;
        printLastOccurrence(a, n);
    }
}
 
// This code is contributed
// by ankita_saini

Python3

# Python 3 program to print the last occurrence
# of every element in relative order
 
# Function to print the last occurrence
# of every element in an array
def printLastOccurrence(a, n):
     
    # used in hashing
    mp = {i:0 for i in range(7)}
 
    # iterate and store the last
    # index of every element
    for i in range(n):
        mp[a[i]] = i
 
    # iterate and check for the last
    # occurrence of every element
    for i in range(n):
        if (mp[a[i]] == i):
            print(a[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
    a = [1, 5, 5, 1, 6, 1]
    n = len(a)
    printLastOccurrence(a, n)
 
# This code is contributed by
# Surendra_Gangwar

C#

// C# program to print the
// last occurrence of every
// element in relative order
using System;
 
class GFG
{
     
// Function to print the last
// occurrence of every element
// in an array
public static void printLastOccurrence(int[] a,
                                       int n)
{
    HashMap<Integer,
            Integer> map = new HashMap<Integer,
                                       Integer>();
     
    // iterate and store the last
    // index of every element
    for (int i = 0; i < n; i++)
        map.put(a[i], i);
         
    for (int i = 0; i < n; i++)
    {
    if (map.get(a[i]) == i)
        Console.Write(a[i] + " ");
    }
}
 
// Driver Code
public static void Main ()
{
    int[] a = { 1, 5, 5, 1, 6, 1 };
    int n = a.Length;
    printLastOccurrence(a, n);
}
}
 
// This code is contributed
// by ChitraNayal

PHP

<?php
// PHP program to print the last
// occurrence of every element
// in relative order
 
// Function to print the last
// occurrence of every element
// in an array
function printLastOccurrence(&$a, $n)
{
 
    // used in hashing
    $mp = array();
 
    // iterate and store the last
    // index of every element
    for ($i = 0; $i < $n; $i++)
        $mp[$a[$i]] = $i;
 
    // iterate and check for the last
    // occurrence of every element
    for ($i = 0; $i < $n; $i++)
    {
        if ($mp[$a[$i]] == $i)
            echo $a[$i] . " ";
    }
}
 
// Driver Code
$a = array(1, 5, 5, 1, 6, 1);
$n = sizeof($a);
printLastOccurrence($a, $n);
 
// This code is contributed
// by ChitraNayal
?>

Javascript

<script>
 
// Javascript program to print the last
// occurrence of every element
// in relative order
 
// Function to print the last
// occurrence of every element
// in an array
function printLastOccurrence(a, n)
{
 
    // used in hashing
    let mp = [];
 
    // iterate and store the last
    // index of every element
    for (let i = 0; i < n; i++)
        mp[a[i]] = i;
 
    // iterate and check for the last
    // occurrence of every element
    for (let i = 0; i < n; i++)
    {
        if (mp[a[i]] == i)
            document.write( a[i] + " ");
    }
}
 
// Driver Code
let a = [1, 5, 5, 1, 6, 1];
let n = a.length;
printLastOccurrence(a, n);
 
 
// This code is contributed by sravan kumar
 
</script>

Producción:  

5 6 1

Tiempo Complejidad : O(N)
Espacio Auxiliar : O(N)

Publicación traducida automáticamente

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