2
* @param {number} capacity4
var LFUCache = function (capacity) {5
this.capacity = capacity;13
LFUCache.prototype.get = function (key) {15
if (!this.capacity) return val;16
const existIndex = this.cache.findIndex((item) => item.key === key);17
if (existIndex > -1) {18
const item = this.cache[existIndex];21
this.cache.splice(existIndex, 1);22
this.cache.unshift(item);29
* @param {number} value32
LFUCache.prototype.put = function (key, value) {33
if (!this.capacity) return;34
const existIndex = this.cache.findIndex((item) => item.key === key);35
if (existIndex > -1) {36
// new item already exists,rewrite the value and increase count37
const existItem = this.cache[existIndex];38
existItem.value = value;40
this.cache.splice(existIndex, 1);41
this.cache.unshift(existItem);43
// new item doesn't exist44
if (this.cache.length === this.capacity) {45
// reach the capacity, need to clear LFU47
let leastCount = this.cache[lfuIndex].count;48
for (let i = 1; i < this.cache.length; i++) {49
const item = this.cache[i];50
if (item.count <= leastCount) {51
leastCount = item.count;55
this.cache.splice(lfuIndex, 1);56
// after clear LFU, push the new item63
// new item can be pushed74
* Your LFUCache object will be instantiated and called as such:75
* var obj = new LFUCache(capacity)76
* var param_1 = obj.get(key)