Beat 100% of the solutions. But I'm sure it's a bug. Is my understanding of the problem wrong? Could someone please enlighten me?


  • 0
    H
    public class LRUCache {
        
        HashMap<Integer,Integer> cache = new HashMap<Integer,Integer>();
        List<Integer> tracker = new ArrayList<Integer>();
        Integer capacity = 0;
        
        public LRUCache(int capacity) {
            this.capacity = capacity;
        }
        
        public int get(int key) {
            if(cache.containsKey(key)){
                Integer latest = new Integer(key);
                tracker.remove(latest);
                
                tracker.add(key);
            
                return cache.get(latest);
            }
            else{
                return -1;
            }
        }
        
        public void set(int key, int value) {
            if(cache.containsKey(key)){
                Integer updateItem = new Integer(key);
                tracker.remove(updateItem);
                tracker.add(key);
                cache.put(key,value);
            }
            else{
                if(tracker.size()==capacity){
                    cache.remove(tracker.get(0));
                    tracker.remove(0);
                }
                tracker.add(key);
                cache.put(key,value);
            }
            
        }
    }
    

Log in to reply
 

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