C
C#4mo ago
Natty

✅ 20/22 Test cases but getting TLE for last two.

https://leetcode.com/problems/lru-cache/description/?envType=list&envId=ep9peqp6
public class LRUCache {

private Dictionary<int, int> cache;
private LinkedList<int> lruTracker;
private readonly int capacity;

public LRUCache(int capacity) {
this.capacity = capacity;
cache = new Dictionary<int, int>(capacity);
lruTracker = new LinkedList<int>();
}

public int Get(int key) {
if (cache.TryGetValue(key, out int val)) {
lruTracker.Remove(key);
lruTracker.AddFirst(key);
return val;
}
else {
return -1;
}
}

public void Put(int key, int value) {

if (cache.ContainsKey(key)) {
cache[key] = value;
lruTracker.Remove(key);
lruTracker.AddFirst(key);
}
else {
if (cache.Count == capacity) {
int lruKey = lruTracker.Last.Value;
lruTracker.RemoveLast();
cache.Remove(lruKey);
}

cache.Add(key, value);
lruTracker.AddFirst(key);
}
}
}

/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.Get(key);
* obj.Put(key,value);
*/
public class LRUCache {

private Dictionary<int, int> cache;
private LinkedList<int> lruTracker;
private readonly int capacity;

public LRUCache(int capacity) {
this.capacity = capacity;
cache = new Dictionary<int, int>(capacity);
lruTracker = new LinkedList<int>();
}

public int Get(int key) {
if (cache.TryGetValue(key, out int val)) {
lruTracker.Remove(key);
lruTracker.AddFirst(key);
return val;
}
else {
return -1;
}
}

public void Put(int key, int value) {

if (cache.ContainsKey(key)) {
cache[key] = value;
lruTracker.Remove(key);
lruTracker.AddFirst(key);
}
else {
if (cache.Count == capacity) {
int lruKey = lruTracker.Last.Value;
lruTracker.RemoveLast();
cache.Remove(lruKey);
}

cache.Add(key, value);
lruTracker.AddFirst(key);
}
}
}

/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.Get(key);
* obj.Put(key,value);
*/
Not sure what else to optimize here. It's all O(1) calls to my knowledge...
1 Reply
Unknown User
Unknown User4mo ago
Message Not Public
Sign In & Join Server To View