思路:
public class LRUCache { private Dictionary_cache; private List _usedKeys; private int _capacity; public LRUCache(int capacity) { _cache = new Dictionary (); _usedKeys = new List (); _capacity = capacity; } public int Get(int key) { if(!_cache.ContainsKey(key)){ return -1; } else{ _usedKeys.Remove(key); _usedKeys.Insert(0, key); return _cache[key]; } } public void Set(int key, int value) { if(_cache.ContainsKey(key)){ _cache[key] = value; _usedKeys.Remove(key); _usedKeys.Insert(0, key); } else{ if(_cache.Keys.Count < _capacity){ _cache.Add(key, value); _usedKeys.Insert(0, key); } else { var removing = _usedKeys.Last(); _usedKeys.RemoveAt(_usedKeys.Count - 1); _cache.Remove(removing); _cache.Add(key, value); _usedKeys.Insert(0, key); } } } }