LFUCache Java实现

 

LRUCache Java实现

 

import java.util.*;
import java.lang.IllegalArgumentException;

public class LFUCache {

	private TreeMap>> countMap = null;
	private HashMap> cache = null;
	private int size;

	public LFUCache(int size){
		if(size <= 0){
			throw new IllegalArgumentException("invalid size");
		}

		cache = new HashMap>(size);
		countMap = new TreeMap>>(new Comparator(){
			@Override
			public int compare(Integer o1, Integer o2){
				return o1 - o2;
			}
		});
		this.size = size;
	}

	public void put(K key, V value){
		if(cache.containsKey(key)){
			Node node = cache.get(key);
			int count = node.getCount();
			node.setCount(count + 1);

			rmCountNode(count, node);
			addCountNode(count + 1, node);
			return;
		}

		if(cache.size() == size){
			Map.Entry>> entry =  countMap.firstEntry();
			Node node = entry.getValue().get(0);
			rmCountNode(node.getCount(), node);
			cache.remove(node.getKey());
		}

		Node node = new Node(key, value);
		cache.put(key, node);
		addCountNode(node.getCount(), node);
		return;
	}

	public V get(K key){
		if(!cache.containsKey(key)){
			return null;
		}

		Node node = cache.get(key);
		rmCountNode(node.getCount(), node);
		addCountNode(node.getCount() + 1, node);
		node.setCount(node.getCount() + 1);
		return node.getValue();
	}

	private void addCountNode(int count, Node node){
		List> list = countMap.get(count);
		if(null == list){
			list = new ArrayList>();
			countMap.put(count, list);
		}
		list.add(node);
	}

	private void rmCountNode(int count, Node node){
		List> list = countMap.get(count);
		if(list.size() == 1){
			countMap.remove(count);
		}else{
			list.remove(node);
		}
	}

	private static class Node{
		private K key;
		private V value;
		private int count;

		public Node(K key, V value){
			this(key, value, 1);
		}

		public Node(K key, V value, int count){
			this.key = key;
			this.value = value;
			this.count = count;
		}

		public K getKey(){
			return key;
		}

		public V getValue(){
			return value;
		}

		public int getCount(){
			return count;
		}

		public void setCount(int count){
			this.count = count;
		}
	}

	
}

 

你可能感兴趣的:(算法题)