Created
October 6, 2022 22:23
-
-
Save bdadam/ff1ba6f57a9083ae5ed48b5e50aaebd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://leetcode.com/problems/lru-cache/submissions/ | |
class LRUCache { | |
obj: Record<number, { val: number; acc: number }>; | |
capacity: number; | |
size: number; | |
acc: number; | |
cache: Record<number, [val: number, acc: number, key: number]>; | |
c: Map<number, [val: number, acc: number]> | |
constructor(capacity: number) { | |
// this.obj = {}; | |
this.capacity = capacity; | |
// this.size = 0; | |
this.acc = 0; | |
// this.cache = {}; | |
this.c = new Map(); | |
} | |
get(key: number): number { | |
const x = this.c.get(key); | |
if (x !== undefined) { | |
x[1] = this.acc++; | |
return x[0]; | |
} | |
return -1; | |
// const item = this.cache[key]; | |
// if (item !== undefined) { | |
// item[1] = this.acc++; | |
// return item[0]; | |
// } | |
// return -1; | |
// const x = this.obj[key]; | |
// if (x !== undefined) { | |
// x.acc = this.acc++; | |
// return x.val; | |
// } | |
// return -1; | |
} | |
put(key: number, value: number): void { | |
// if (!this.c.has(key)) { | |
// this.size++; | |
// } | |
this.c.set(key, [value, this.acc++]); | |
if (this.c.size > this.capacity) { | |
let lowestKey = -1; | |
let lowestAcc = Infinity; | |
for (const [k, item] of this.c.entries()) { | |
if (item[1] < lowestAcc) { | |
lowestAcc = item[1]; | |
lowestKey = k; | |
} | |
} | |
this.c.delete(lowestKey); | |
} | |
// return; | |
// if (this.cache[key] === undefined) { | |
// this.size +=1; | |
// } | |
// if (this.size > this.capacity) { | |
// let lowestKey = -1; | |
// let lowestAcc = Infinity; | |
// for (const x in this.cache) { | |
// if (this.cache[x][1] < lowestAcc) { | |
// lowestAcc = this.cache[x][1]; | |
// lowestKey = this.cache[x][2]; | |
// } | |
// } | |
// delete this.cache[lowestKey]; | |
// this.size = this.capacity; | |
// } | |
// this.cache[key] = [value, this.acc++, key]; | |
// return; | |
// if (this.obj[key] === undefined) { | |
// this.size += 1; | |
// } | |
// if (this.size > this.capacity) { | |
// let lowestKey = -1; | |
// let lowestAcc = Infinity; | |
// for (const x in this.obj) { | |
// if (this.obj[x].acc < lowestAcc) { | |
// lowestAcc = this.obj[x].acc; | |
// lowestKey = Number(x); | |
// } | |
// } | |
// delete this.obj[lowestKey]; | |
// this.size = this.capacity; | |
// } | |
// this.obj[key] = { val: value, acc: this.acc++ }; | |
} | |
} | |
/** | |
* Your LRUCache object will be instantiated and called as such: | |
* var obj = new LRUCache(capacity) | |
* var param_1 = obj.get(key) | |
* obj.put(key,value) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment