Why isn't my code working?


  • 0
    D

    I hash the key to a 2 element array that contains [value, numberOfTimesAccessed]. In get I update for the number of times accessed for the key (if it exists in the map). In set, if the capacity is reached, I find the key with the lowest number of number of times accessed and delete it.

    import java.util.HashMap;
    import java.util.PriorityQueue;
    public class LRUCache {
        private int capacity;
        private int size;
        private HashMap<Integer, int[]> map = new HashMap<Integer, int[]>();
        public LRUCache(int capacity) {
            this.capacity = capacity;
        }
        
        public int get(int key) {
            int val = -1;
            if(map.containsKey(key)){
                val = map.get(key)[0];
                map.get(key)[1] += 1;
            }
            return val;
        }
        
        public void set(int key, int value) {
            if(this.get(key) != -1) {
                map.get(key)[0] = value;
            }
            else if (this.get(key) == -1 && size < this.capacity)
            {
                int[] val = new int[2];
                val[0] = value;
                val[1] = 1;
                map.put(key, val);
                size++;
            }
            else if(this.get(key) == -1 && size == this.capacity)
            {
                int min = Integer.MAX_VALUE;
                int del = 0;
                for(int k: map.keySet()){
                    if(map.get(k)[1] < min)
                    {
                        min = map.get(k)[1];
                        del = k;
                    }
                }
                map.remove(del);
                size--;
                this.set(key, value);
            }
        }
    }
    

Log in to reply
 

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