using System.Collections.Generic;
using System.Security.Cryptography;
namespace csharp_leetcode
public Node(int i, int j) { key = i; val = j; }
public int key { get; set; }
public int val { get; set; }
Dictionary<int, LinkedListNode<Node>> dict = new Dictionary<int, LinkedListNode<Node>>();
LinkedList<Node> lru = new LinkedList<Node>();
public LRUCache(int capacity)
if (dict.ContainsKey(key))
Node nd = dict[key].Value;
int val = dict[key].Value.val;
this.LRU_AddToFirst(key, val);
public void Put(int key, int value)
if (dict.ContainsKey(key))
dict[key].Value.val = value;
this.LRU_AddToFirst(key, value);
if (lru != null && lru.Count == iCapacity) this.LRU_RemoveFromLast();
this.LRU_AddToFirst(key, value);
private void LRU_AddToFirst(int key, int value)
Node nd = new Node(key, value);
LinkedListNode<Node> llnode = new LinkedListNode<Node>(nd);
if (dict.ContainsKey(key)) dict[key] = lru.First;
else dict.Add(key, lru.First);
private void LRU_RemoveFromLast()
Node nd = lru.Last.Value;
foreach (int key in dict.Keys)
Console.Write($"[{key}, {dict[key].Value.val}], ");
Console.Write($"{nd.key}:{nd.val} ");
public class LC_0146_lru_cache
public static void Main()
List<string> lstcmd = new List<string>() { "LRUCache", "put", "put", "put", "put", "get", "get" };
int[][] lstcmdval = { new int[] { 2 }, new int[] { 2, 1 }, new int[] { 1, 1 }, new int[] { 2, 3 }, new int[] { 4, 1 }, new int[] { 1 }, new int[] { 2 } };
LRUCache oLRUCache = null;
for (int i = 0; i < lstcmd.Count; i++)
int[] cmdval = lstcmdval[i];
string tmpstr = (cmdval.Length > 1) ? $"{cmdval[0]}, {cmdval[1]}" : $"{cmdval[0]}";
Console.WriteLine($"{cmd}, {tmpstr}");
if (cmd == "LRUCache") oLRUCache = new LRUCache(cmdval[0]);
else if (cmd == "get") Console.WriteLine(oLRUCache.Get(cmdval[0]));
else if (cmd == "put") oLRUCache.Put(cmdval[0], cmdval[1]);
void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
Could you do get and put in O(1) time complexity?
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
[null, null, null, 1, null, -1, null, -1, 3, 4]
LRUCache lRUCache = new LRUCache(2);
At most 3 * 104 calls will be made to get and put.