上海建设工程安全监理网站,社交网站用户体验,投放广告的渠道有哪些,企业信息查询公示系统LFU
LFU算法是最近最少使用次数算法#xff0c;针对的是使用次数#xff1b; 补充一点#xff1a;对于相同使用次数应该需要加上时间戳#xff0c;看他人实现LFU算法都没有考虑这一点。 本文通过全局nextId来表示第几次使用功能#xff1b;
class LFU {constructor(capa…LFU
LFU算法是最近最少使用次数算法针对的是使用次数 补充一点对于相同使用次数应该需要加上时间戳看他人实现LFU算法都没有考虑这一点。 本文通过全局nextId来表示第几次使用功能
class LFU {constructor(capacity) {this.capacity capacity;this.cache [];this.nextId 1; // 用于表示第几次存储的区分相同存储次数}get(key) {let value -1;this.cache.some((cache) {if (cache.key key) {value cache.value;cache.count;cache.useId this.nextId;this.nextId;return true;}return false;});return value;}set(key, value) {let minCountIndex;let hasKey false;for(let i 0; ithis.cache; i) {const item this.cache[i];if (item.key key) {hasKey true;item.value value;item.count;item.useId this.nextId;this.nextId;return;}if (index 0) {minCountIndex 0;} else {const minItem this.cache[minCountIndex];if (minItem.count item.count ||(minItem.count item.count minItem.useId item.useId)) {minCountIndex i;}}}if (!hasKey) {if (this.cache.length this.capacity) {this.cache.splice(minCountIndex, 1);}this.cache.unshift({key, value, count: 1, useId: this.nextId});this.nextId;}}}const lfu new LFU(2);lfu.set(key1, value1);
lfu.get(key1);
lfu.set(key2, value2);
lfu.set(key3, value3);
lfu.set(key4, value4);
lfu.get(key4);
console.log(lfu, lfu);