Created
April 16, 2021 20:39
-
-
Save LDuncAndroid/13bbf3414de5cf9aaf4db300fd1a3e70 to your computer and use it in GitHub Desktop.
LRU Cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LRUCache(capacity: Int) { | |
private val internalCache: LinkedHashMap<Int, Int> = | |
object : LinkedHashMap<Int, Int>(initialCapacity = capacity, loadFactor = 0.75f, accessOrder = true) { | |
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, Int>?): Boolean { | |
return size > capacity | |
} | |
} | |
fun get(key: Int) = internalCache.getOrDefault(key, -1) | |
fun set(key: Int, value: Int) = internalCache.putIfAbsent(key, value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment