A photo gallery keeps decoded images in memory, but only capacity of them. When a new image must be stored and the cache is full, it throws out the image that was used (read or stored) least recently. Write a class ImageCache:
new ImageCache(capacity) creates an empty cache.get(id) returns the stored size for image id, or -1 if it isn't cached. A successful get counts as a use.put(id, size) stores or replaces image id with size and counts as a use. If this makes the cache hold more than capacity images, remove the least recently used one.Both methods must run in O(1) average time.
Each example lists the calls in order, then each call's arguments. The first call creates the object with new ImageCache(…); the output lists what each call returns (null for the constructor and for methods that return nothing).
Input: ["ImageCache","put","put","get","put","get","put","get","get","get"] [[2],[1,100],[2,200],[1],[3,300],[2],[4,400],[1],[3],[4]] Output: [null,null,null,100,null,-1,null,-1,300,400]
Reading image 1 makes image 2 the stalest, so storing 3 evicts 2. Storing 4 then evicts 1.
Input: ["ImageCache","get"] [[1],[5]] Output: [null,-1]
Nothing is cached yet.
1 <= capacity <= 30000 <= id <= 10^40 <= size <= 10^52 * 10^5 calls.Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #693 Image Cache With Least-Recent Eviction. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.