A C# Solution with 2 Lists


  • 0
    L
    public class LRUCache {
    
        private List<int> lstCache;
        private List<int> lstIndex;
        private int cap;
        public LRUCache(int capacity) {
            cap = capacity;
            lstIndex = new List<int>();
            lstCache = new List<int>();
        }
    
        public int Get(int key) {
            if(!lstIndex.Contains(key)) return -1;
            int index = lstIndex.IndexOf(key);
            int value = lstCache[index];
            lstIndex.RemoveAt(index);
            lstCache.RemoveAt(index);
            lstIndex.Add(key);
            lstCache.Add(value);
            return value;
        }
    
        public void Set(int key, int value) {
            if(lstIndex.Contains(key))
            {
                int index = lstIndex.IndexOf(key);
                lstIndex.RemoveAt(index);
                lstCache.RemoveAt(index);
            }
            if(cap == lstIndex.Count)
            {
                lstIndex.RemoveAt(0);
                lstCache.RemoveAt(0);
            }
            lstIndex.Add(key);
            lstCache.Add(value);
        }
    }

Log in to reply
 

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