Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param {number} capacity
- */
- var LFUCache = function(capacity) {
- this.capacity = capacity;
- this.count = 0;
- this.frequency = {};
- this.sorted = [];
- };
- /**
- * @param {number} key
- * @return {number}
- */
- LFUCache.prototype.get = function(key) {
- if (this[key]) {
- this.count ++;
- if (!this.frequency[key]) {
- this.frequency[key] = {
- 'recent': this.count,
- 'number': 1
- }
- } else {
- this.frequency[key]['recent'] = this.count;
- this.frequency[key]['number'] ++;
- }
- return this[key];
- } else {
- return -1
- }
- };
- /**
- * @param {number} key
- * @param {number} value
- * @return {void}
- */
- LFUCache.prototype.put = function(key, value) {
- if (this.length < this.capacity) {
- this[key] = value;
- } else {
- for (var key in this.frequency) {
- this.sorted.push([key, this.frequency[key]])
- }
- this.sorted.sort((a,b)=>{
- return a[1]['number']-b[1]['number']===0 ? a[1]['recent']-b[1]['recent'] : a[1]['number']-b[1]['number'];
- })
- if (this.sorted[0]!==undefined) {
- let deleteKey = this.sorted[0][0];
- delete this.frequency[deleteKey];
- delete this[deleteKey];
- }
- this[key] = value;
- console.log(this.sorted)
- }
- };
Add Comment
Please, Sign In to add comment