Simple solution using ArrayList and HashMap java


  • 0
    7

    """public class LRUCache {
    HashMap<Integer,Integer> map ;
    List<Integer> list ;
    int cap;

    public LRUCache(int capacity) {
        map = new HashMap<Integer,Integer>();
        list = new ArrayList<>();
        cap = capacity;
    }
    
    public int get(int key) {
        if(map.containsKey(key)){
            list.remove(list.indexOf(key));
            list.add(key);
            return map.get(key);
        }
        return -1;
    }
    
    public void put(int key, int value) {
           if(map.containsKey(key)){
               list.remove(list.indexOf(key));
               list.add(key);
               map.put(key,value);
           }else{
               if(list.size()==cap){
                    map.remove(list.get(0));
                    list.remove(0);
                    list.add(key);
                    map.put(key,value);
                   
               }else{
                  map.put(key,value);
                  list.add(key);
               }
               
           }
    }
    

    }

    /**

    • Your LRUCache object will be instantiated and called as such:
    • LRUCache obj = new LRUCache(capacity);
    • int param_1 = obj.get(key);
    • obj.put(key,value);
      */"""

Log in to reply
 

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