Clean Java Implementation


  • 0
    A
    public class LRUCache {
    
    Map<Integer, Integer> map;
    int capacity;
    
    public LRUCache(int capacity) {
    	this.capacity = capacity;
    	map = new LinkedHashMap<Integer, Integer>();
    }
    
    public int get(int key) {
    	if (map.containsKey(key)) {
    		Integer v = map.get(key);
    		map.remove(key);
    		map.put(key, v);
    		return v;
    	}
    	return -1;
    }
    
    public void set(int key, int value) {
    	if (map.containsKey(key)) {
    		Integer v = map.get(key);
    		map.remove(key);
    		map.put(key, value);
    	} else {
    		if (map.keySet().size() == capacity)
    			map.remove(map.keySet().iterator().next());
    		map.put(key, value);
    	}
    }
    }

Log in to reply
 

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