Advertisement
joespi

Untitled

Feb 12th, 2021
796
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.59 KB | None | 0 0
  1. int firstDuplicate(int[] a) {
  2.  
  3.     int minimo=-1;
  4.    
  5.     // Creamos un hashset para almacenar los números del array y contar las repeticiones.
  6.    
  7.     HashSet<Integer> set = new HashSet<>();
  8.    
  9.     // Recorremos el array de derecha a izquierda
  10.     for(int i=a.length-1; i>=0; i--)
  11.     {        
  12.         // Si el elemento i está en el hash set, lo asignamos al mínimo
  13.         if (set.contains(a[i]))
  14.             minimo = i;
  15.  
  16.         else  // Sino agregamos el elemento al hash set
  17.             set.add(a[i]);
  18.    }
  19.    
  20.    if (minimo != -1) return a[minimo];
  21.     else return minimo;
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement