C# linkedlist + Dictionary, clear and simple, btw short but unclear coding sucks!


  • 0
    D
    public class LRUNode{
        public int Key; 
        public int Value;
        public LRUNode(int key, int value){
            Key = key;
            Value = value;
        }
    }
    public class LRUCache {
        private int _capacity = 0;
        private LinkedList<LRUNode> _list = new LinkedList<LRUNode>();
        private Dictionary<int, LRUNode> _dict = new Dictionary<int, LRUNode>();
        public LRUCache(int capacity) {
            _capacity = capacity;
        }
    
        public int Get(int key) {
            if (!_dict.ContainsKey(key)){
                return -1;
            }
            
            LRUNode node = _dict[key];
            _list.Remove(node);
            _list.AddFirst(node);
            
            return _dict[key].Value;
        }
    
        public void Set(int key, int value) {
            if (!_dict.ContainsKey(key)){
                if (_list.Count == _capacity){
                    int lastKey = _list.Last().Key;
                    _list.RemoveLast();
                    _dict.Remove(lastKey);
                }
                LRUNode newNode = new LRUNode(key, value);
                _list.AddFirst(newNode);
                _dict.Add(key, newNode);
            }
            else{
                _dict[key].Value = value;
                LRUNode node = _dict[key];
                _list.Remove(node);
                _list.AddFirst(node);
                
            }
        }
    }

  • 0
    R

    why

    _dict[key].Value = value; LRUNode node = _dict[key]; _list.Remove(node); _list.AddFirst(node);

    the segment is right ?

    _list will find the new one (node)?


    yeah, I got it.
    _dict and _list hold the same obj.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.