本文主要是介绍js实现LFU算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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; i<this.cache.length; 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);
这篇关于js实现LFU算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!