Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Implementando la clase de conjuntos aleatorios con la operación O(1)

Esto está relacionado con leetcode - question here , que pregunta:

Implemente la clase RandomizedSet:

  • RandomizedSet() Inicializa el objeto RandomizedSet.
  • bool insert(int val) Inserta un elemento val en el conjunto si no está presente. Devuelve verdadero si el elemento no estaba presente, falso en caso contrario.
  • bool remove(int val) Elimina un elemento val del conjunto si está presente. Devuelve verdadero si el elemento estaba presente, falso en caso contrario.
  • int getRandom() Devuelve un elemento aleatorio del conjunto actual de elementos (se garantiza que al menos un elemento existe cuando se llama a este método). Cada elemento debe tener la misma probabilidad de ser devuelto.

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() */
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!