Skip to content

Instantly share code, notes, and snippets.

@kennyxcao
Created November 2, 2017 16:58
Show Gist options
  • Save kennyxcao/5a93f97df32d90b0245b0fba7bae2b5c to your computer and use it in GitHub Desktop.
Save kennyxcao/5a93f97df32d90b0245b0fba7bae2b5c to your computer and use it in GitHub Desktop.
/**
* @param {number} capacity
*/
var LFUCache = function(capacity) {
this.capacity = capactiy;
this.storage = {};
this.freq = {};
this.lastVisited = [];
};
/**
* @param {number} key
* @return {number}
*/
LFUCache.prototype.get = function(key) {
if (!this.storage[key]) {
return -1;
} else {
this.freq[key] += 1;
this.lastVisited.push(key);
return this.storage[key];
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LFUCache.prototype.put = function(key, value) {
var lfuKey;
if (!this.capacity) {
var leastFreqKeys = [];
var leastCount = +Infinity;
for (var key in this.freq) {
if (this.freq[key] < leastCount) {
leastCount = this.freq[key];
leastFreqKeys = [key];
} else if (this.freq[key] === leastCount) {
leastFreqKeys.push(key);
}
}
if (leastFreqKeys.length === 1) {
lfuKey = leastFreqKeys[0];
} else {
var leastVisited;
var leastVisitedIndex = +Infinity;
for (var i = 0; i < leastFreqKeys.length; i++) {
if (this.lastVisited.lastIndexOf(leastFreqKeys[i]) < leastVisitedIndex) {
}
}
for (var i = lastVisited.length - 1; i >= 0; i--) {
if (leastFreqKeys.includes[lastVisited[i]]) {
}
}
}
}
};
/**
* Your LFUCache object will be instantiated and called as such:
* var obj = Object.create(LFUCache).createNew(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
var cache = new LFUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
console.log(cache.get(1)); // returns 1
cache.put(3, 3); // evicts key 2
console.log(cache.get(2)); // returns -1 (not found)
console.log(cache.get(3)); // returns 3.
cache.put(4, 4); // evicts key 1.
console.log(cache.get(1)); // returns -1 (not found)
console.log(cache.get(3)); // returns 3
console.log(cache.get(4)); // returns 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment