Ver Mensaje Individual
  #3 (permalink)  
Antiguo 14/12/2013, 07:18
Pantaláimon
 
Fecha de Ingreso: julio-2006
Ubicación: Barcelona
Mensajes: 244
Antigüedad: 17 años, 9 meses
Puntos: 32
Respuesta: Propuesta para desafíos javascript 2014

Como lo más evidente era tirar de API yo he escogido otro camino.

Código Javascript:
Ver original
  1. var sink = function ( array, i ) {
  2.     var n = array.length;
  3.     var j = 2*i+1;
  4.     var k = j + 1;
  5.     var item = array[i];
  6.     while( j < n ) {
  7.         if( k < n && array[k] < array[j] ) j = k;
  8.         if( item > array[j] ) {
  9.             array[i] = array[j];
  10.             array[j] = item;
  11.         }
  12.         i = j;
  13.         j = 2*i+1;
  14.         k = j + 1;
  15.         item = array[i];
  16.     }
  17. }
  18.  
  19. Array.prototype.toHeap = function() {
  20.     var n = (this.length >> 1) - 1;
  21.     for( ; n >= 0; --n ) {
  22.         sink( this, n );
  23.     }
  24. }
  25.  
  26. Array.prototype.popMin = function()
  27. {
  28.     var n = this.length;
  29.     if( n > 0 ) {
  30.         this[0] = this[n-1];
  31.         this.pop();
  32.         sink( this, 0 );
  33.     }
  34.  
  35. }
  36.  
  37. function tercero( arr ) {
  38.     if( arr.length < 3 ) {
  39.         return false;
  40.     } else {
  41.         arr.toHeap();
  42.         var n = 1;
  43.         do {
  44.             var value = arr[0];
  45.             arr.popMin();
  46.             if( arr[0] != value ) ++n;
  47.         } while( n < 3 )
  48.  
  49.         return arr[0];
  50.     }
  51. }
  52.  
  53. var datos = [4,1,7,2];
  54. console.log(tercero(datos));

Edit: vaya que despiste, no me di cuenta del tema de que números repetidos eran considerados como uno solo. Ya está corregido

Última edición por Pantaláimon; 14/12/2013 a las 07:42