C# Need help with Time Limit Exceeded..


  • 0
    S

    I don't create a "Node" but just store the key in the LinkedList and the Key,Value Pair in the Dictionary.
    The methods I used is similiar to this post : https://leetcode.com/discuss/40426/linkedlist-dictionary-clear-simple-short-unclear-coding-sucks

    Why do I get TLE? And why do people create a class Node?
    I tried the below code in Visual Studio and it's even faster than the code from the link above.

    Thanks

    public class LRUCache {
    
    public Dictionary<int,int> dict=new Dictionary<int,int>();
    public LinkedList<int> ll= new LinkedList<int>();
    public int cap=0;
    
    public LRUCache(int capacity) {
        cap = capacity;
    }
    
    public int Get(int key) {
        if(!dict.ContainsKey(key)){
            return -1;
        }else{
            ll.Remove(key);
            ll.AddFirst(key);
            return dict[key];
        }
    }
    
    public void Set(int key, int value) {
        if(!dict.ContainsKey(key)){
            if(ll.Count==cap){
                dict.Remove(ll.Last());
                ll.RemoveLast();
            }
            dict.Add(key,value);
            ll.AddFirst(key);
    
    
    
        }
        else{
                        
            dict[key]=value;
            ll.Remove(key);
            ll.AddFirst(key);
        }
    }
    }

Log in to reply
 

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