Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
LRU cache - Simple solution (costly)
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class LRUCache{ int size; int counter; Map<Integer,Integer> dict = new HashMap<Integer,Integer>(); Map<Integer,Integer> priority = new HashMap<Integer,Integer>(); public LRUCache(int size){ this.size = size; counter = 0; } public int get(int key){ if(!dict.containsKey(key)) return -1; int out = dict.get(key); priority.put(key,counter); counter++; return out; } public void put(int key,int value){ //check if data structure is full if(dict.size()==size&&!dict.containsKey(key)){ //remove one int min=Integer.MAX_VALUE,minItem=Integer.MAX_VALUE; //find min priority for(int item:priority.keySet()){ if(priority.get(item)<=min){ min = priority.get(item); minItem = item; } } priority.remove(minItem); dict.remove(minItem); } dict.put(key,value); priority.put(key,counter); counter++; } public void printDS(){ for(int item:dict.keySet()){ System.out.println(item+"->"+dict.get(item)+" :"+priority.get(item)); } } } class Rextester { public static void main(String args[]) { System.out.println("Hello, World!"); LRUCache obj = new LRUCache(4); obj.put(20,1); obj.put(30,2); obj.put(40,3); obj.put(50,4); obj.put(30,5); obj.put(60,6); System.out.println(obj.get(50)); obj.put(70,7); obj.printDS(); System.out.println(obj.get(25)); } }
run
|
edit
|
history
|
help
0
Catalan number optimised
exp5
Hello world
Problem: rstring
My1
Fireball Plugin
boolean1
pass
Bank System
상속1