[Java] Using Date to find LRU, not working.


  • 0
    N

    Here is my code

    import java.util.Date;
    import java.util.Hashtable;
    import java.util.Map;
    
    public class LRUCache {
    
        Hashtable<Integer, Integer> values;
        private int capacity;
        Hashtable<Integer, Date> timeStamps;
    
        public LRUCache(int capacity) {
            values = new Hashtable<>(capacity);
            timeStamps = new Hashtable<>(capacity);
            this.capacity = capacity;
        }
    
        public int get(int key) {
            if (values.containsKey(key)) {
                timeStamps.put(key, new Date());
                return values.get(key);
            } else
                return -1;
        }
    
        public void set(int key, int value) {
            if(capacity == 0) return;
            if (values.size() >= capacity) {
                int lruKey = findLRUKey();
                values.remove(lruKey);
            }
            values.put(key, value);
            timeStamps.put(key, new Date());
    
        }
    
        private int findLRUKey() {
            Date oldest = new Date();
            int lruKey = 0;
            for(Map.Entry<Integer, Date> entry: timeStamps.entrySet()){
                if(entry.getValue().before(oldest)){
                    oldest = entry.getValue();
                    lruKey = entry.getKey();
                }
            }
            return lruKey;
        }
    }
    

    The output is inconsistent.
    For input 1, set [2,1], get 2, set [3,1], get 2, get 3
    Sometimes output is 1, 1, 2 (incorrect) and sometimes it is 1, -1, 2 (correct)

    Can anyone explain why there is this inconsistency?


Log in to reply
 

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