My java solution without Double linked List


  • 0
    Q

    public class LRUCache {
    private HashMap<Integer, Integer> map;
    private ArrayList<Integer> list;
    private int size;
    public LRUCache(int capacity) {
    map = new HashMap<>();
    list = new ArrayList<>();
    size = capacity;
    }

    public int get(int key) {
        if (map.containsKey(key)){
            list.remove(new Integer(key));
            list.add(0, key);
            return map.get(key);
        } else {
            return -1;
        }
    }
    
    public void set(int key, int value) {
        if (!map.containsKey(key)){
            if (list.size() < size) {
                list.add(0, key);
            } else {
                int temp = list.remove(list.size() - 1);
                map.remove(temp);
                list.add(0, key);
            }
        } else {
            list.remove(new Integer(key));
            list.add(0, key);
        }
        map.put(key, value);
    }
    

    }


Log in to reply
 

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