C# queue/map solution


  • 0
    M
    public class LRUCache {
        Queue<int> m_q = new Queue<int>();
        Dictionary<int, int> m_valMap = new Dictionary<int,int>();
        Dictionary<int, int> m_usedMap = new Dictionary<int, int>();
        int m_c;
    
        public LRUCache(int capacity) {
            m_c = capacity;
        }
    
        public int Get(int key) {
            if (m_valMap.ContainsKey(key))
            {
                m_q.Enqueue(key);
                m_usedMap[key]++;
                return m_valMap[key];
            } else {
                return -1;
            }
        }
    
        public void Set(int key, int value) {
            m_q.Enqueue(key);
            
            if (m_valMap.ContainsKey(key)) {
                m_usedMap[key]++;
            } else {
                m_usedMap.Add(key, 1);
                
                if (m_valMap.Count == m_c) {
                    while(true) {
                        var k = m_q.Dequeue();
                        if (m_usedMap[k] > 1) {
                            m_usedMap[k]--;
                        } else {
                            m_usedMap.Remove(k);
                            m_valMap.Remove(k);
                            break;
                        }
                    }
                }
            }
            
            m_valMap[key] = value;
        }
    }

Log in to reply
 

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