[java] Accepted solution, but is this valid?


  • 3
    C

    For java programmers, this problem can be easily solved by using a LinkedHashMap. But what's the point then?

    public class LRUCache {
    private Map<Integer, Integer> pairs;
    private int capacity;
    
    public LRUCache(int c) {
        this.capacity = c;
        this.pairs = new LinkedHashMap<Integer, Integer>() {
            protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
                return size() > capacity;
            }
        };
    }
    
    public int get(int key) {
        if (pairs.containsKey(key)) {
            int value = pairs.get(key);
            pairs.remove(key);
            pairs.put(key, value);
            return pairs.get(key);
        }
        else {
            return -1;
        }
    }
    
    public void set(int key, int value) {
        if (pairs.containsKey(key)) {
            pairs.remove(key);
        }
        pairs.put(key, value);
    }
    

    }


  • 0
    P

    You have problems understanding of removeEldestEntry, please reference https://leetcode.com/discuss/1188/java-is-linkedhashmap-considered-cheating


Log in to reply
 

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