Esto está relacionado con leetcode - question here , que pregunta:
Implemente la clase RandomizedSet:
Debe implementar las funciones de la clase de manera que cada función funcione con una complejidad de tiempo promedio de O(1).
Puedo pasar algunos de los casos de prueba pero falla uno de los casos de prueba (donde en algunos lugares, mi programa devuelve undefined ). ¿Qué es lo que estoy haciendo mal aquí? No puedo encontrar mi error.
var RandomizedSet = function() { this.map = new Map(); this.vector = []; }; /** * @param {number} val * @return {boolean} */ RandomizedSet.prototype.insert = function(val) { if(this.map.has(val)) return false; else { let position = 0; if(this.vector.length > 0) position = this.vector.length-1; this.map.set(val, position); this.vector.push(val); return true; } }; /** * @param {number} val * @return {boolean} */ RandomizedSet.prototype.remove = function(val) { if(this.map.has(val)) { const index = this.map.get(val); const lastVal = this.vector[this.vector.length-1]; this.vector[index] = lastVal; this.vector.pop(); this.map.delete(val); return true; }else { return false; } }; /** * @return {number} */ RandomizedSet.prototype.getRandom = function() { const randIndex = Math.floor(Math.random() * this.vector.length); return this.vector[randIndex]; }; /** * Your RandomizedSet object will be instantiated and called as such: * var obj = new RandomizedSet() * var param_1 = obj.insert(val) * var param_2 = obj.remove(val) * var param_3 = obj.getRandom() */Al mover el último elemento al lugar del elemento eliminado, olvidó actualizar el índice del elemento movido en el mapa:
RandomizedSet.prototype.remove = function(val) { if(this.map.has(val)) { const index = this.map.get(val); const lastVal = this.vector[this.vector.length-1]; this.vector[index] = lastVal; this.vector.pop(); this.map.set(lastVal, index); // ADDED this.map.delete(val); return true; }else { return false; } }; Tenga en cuenta el index == this.vector.length-1 ; el orden de operaciones que se muestra arriba manejará este caso correctamente sin código adicional.