class Node{ int key; int val; int weight; int timeStamp;
public Node(int key, int val, int weight, int timeStamp) { this.key = key; this.val = val; this.weight = weight; this.timeStamp = timeStamp; } }
public class Cache { int capacity; int timeStamp; Map<Integer,Node> nodeMap; //k-v mapping PriorityQueue<Node> prque; //store the node
public Cache(int capacity){ this.capacity = capacity; this.timeStamp = 0; nodeMap = new HashMap<>(); Comparator<Node> timeWeightComparator = new Comparator<Node>() { //rewrite the priority @Override public int compare(Node o1, Node o2) { return (int) (o1.weight / (Math.log(o1.timeStamp - o2.timeStamp + 1) + 1) - (o2.weight / (Math.log(o2.timeStamp - o1.timeStamp + 1) + 1))); } }; prque = new PriorityQueue<>(timeWeightComparator); }
public int get(int key){ //时间复杂度O(1), hashmap.get为O(1) if (!nodeMap.containsKey(key)){ return -1; } Node getNode = nodeMap.get(key); getNode.timeStamp = ++timeStamp; return getNode.val; }
void put(int key, int val, int weight){ //最好的情况是已经包含这个键了,时间复杂度为O(1) if (this.capacity <= 0){ return; } if (nodeMap.containsKey(key)){ Node newNode = nodeMap.get(key); newNode.val = val; newNode.weight = weight; newNode.timeStamp = ++ timeStamp; }else { if (nodeMap.size() == capacity){ Node leastNode = prque.poll(); //O(logN) assert leastNode != null; nodeMap.remove(leastNode.key); } Node newNode = new Node(key, val, weight, ++timeStamp); prque.add(newNode); nodeMap.put(key,newNode); }
}
public static void main(String[] args) { //test case Cache cache = new Cache(5); cache.put(0,15,3); cache.put(1,28,10); cache.put(2,16,4); cache.put(3,4,6); cache.put(4,75,5); cache.put(4,100,100); System.out.println(cache.get(1)); System.out.println(cache.get(2)); System.out.println(cache.get(3)); System.out.println(cache.get(4)); System.out.println(cache.get(0));
} }
BigO notation analysis
get
The get operation is base on the hashmap.get(key). So, the time complexity is O(1).
put
The put operation can be seperated to follow two case:
1. Don’t need insert a new node (when the key is exist)
In this case, we only need to get the node from hashmap and update it. The time complexity is O(1).
2. Insert new Node
If the capcity is not reached. we can insert a new node directly. the complexity is O(logN) + O(1) = O(logN) —- (O(logN) for priorityque, O(1) for hashmap).
If the capicity is reached. we need to poll a node with least score, the time complexity is O(logN). Then inster a new node. The time complexity is O(logN) + O(logN) + O(1) = O(logN).
Maybe you could buy me a cup of coffee.
Scan this qrcode
Open alipay app scan this qrcode, buy me a coffee!
Scan this qrcode
Open wechat app scan this qrcode, buy me a coffee!