Example
For
a = [2, 3, 3, 1, 5, 2]
, the output should befirstDuplicate(a) = 3
.There are 2 duplicates: numbers
2
and3
. The second occurrence of3
has a lower rate than the second occurrence of2
, so that the answer is3
.For
a = [2, 4, 3, 5, 1]
, the output should befirstDuplicate(a) = -1
.Entry / Exit
[time limit] 3000ms (java) [entry]
array.integer a
Guaranteed Restrictions:
1 ≤ a.length ≤ 10^5
,1 ≤ a[i] ≤ a.length
.[exit]
integer
The element in
a
that occurs in the array more than once and that has the minimum rate for its second occurrence. If there is no such element, returns-1
.
The issue is not to find the duplicates, but to improve the speed of response, since the system that tests my algorithms, generates random data with many records, so that if you use many lines of code or the same does not is optimal, it happens that you exceed the maximum time of 3 sec when the code is tested in each random task generated by the system. I would like to know how to improve this code.
int firstDuplicate(int[] a) {
int numero = -1; //coloco un valor por defecto
int indice = 100000; //agrego un valor maximo
int i = 0; // y un contador
for(int valor : a){// recorro todos los valores del registro que pueden ser muchos
if(i >= indice) break; // si el indice del numero es igual al valor de recorrido, termina el analisis.
if( numero != a[i] ){ // solo si el vecino no es igual lo analizo
for(int n=(i+1); n<a.length; n++){ // cada vez que analizon un valor, desde alli analizo el resto de los vecino para ver si hay duplicados
if(valor == a[n] && n < indice){ // si el valor esta duplicado pero el indice es menor al duplicado anterior. Entonces lo guardas.
indice = n;
numero = valor;
break;
}
}
}
i++;
}
return numero;
}
For more details you can see it in CodeFight