Implementazione di cache LRU in JavaScript
Livello 5546 battiture
La cache LRU elimina l'elemento meno recentemente usato quando la capacità viene superata.
Codice JavaScript
// Cache LRU (Least Recently Used) usando Map1class LRUCache {2 constructor(capacity) { // Impostare il numero massimo di elementi3 this.capacity = capacity; // Map mantiene l'ordine di inserimento4 this.cache = new Map();5 }6 get(key) { // Restituire -1 se la chiave non esiste7 if (!this.cache.has(key)) return -1; // Ottenere il valore8 const val = this.cache.get(key); // Spostare alla fine (usato più recentemente) reinserendo9 this.cache.delete(key);10 this.cache.set(key, val);11 return val;12 }13 put(key, value) { // Eliminare se esiste (per aggiornare la posizione)14 this.cache.delete(key); // Aggiungere alla fine (usato più recentemente)15 this.cache.set(key, value); // Se oltre la capacità, rimuovere il più vecchio (primo)16 if (this.cache.size > this.capacity) { // keys().next().value è la prima chiave (la più vecchia)17 this.cache.delete(this.cache.keys().next().value);18 }19 }20}21 // Creare cache con capacità 222const cache = new LRUCache(2);// Aggiungere elementi23cache.put(1, "a"); cache.put(2, "b");// Ottenere 1 (lo rende usato più recentemente)24console.log(cache.get(1));// Aggiungere 3, elimina 2 (usato meno recentemente)25cache.put(3, "c");// 2 è stato eliminato, restituisce -126console.log(cache.get(2));Output
a -1
Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice JavaScript e quante volte compaiono.
.× 30(× 23)× 23;× 16,× 6"× 6{× 5}× 5=× 4-× 1