Created
November 11, 2020 00:01
-
-
Save vovahost/75567435c7571328dda8727698071cb5 to your computer and use it in GitHub Desktop.
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
import java.util.* | |
class LRUCache<K, T>(private val capacity: Int) { | |
private val map: LinkedHashMap<K, T> = LinkedHashMap() | |
operator fun get(key: K): T? { | |
val value = map[key] | |
if (value != null) { | |
this[key] = value | |
} | |
return value | |
} | |
operator fun set(key: K, value: T?) { | |
when { | |
// Null value provided, remove the key-value from the cache. | |
value == null -> { | |
map.remove(key) | |
} | |
// The cache already contains the key, remove it before inserting, to rearrange to the top. | |
map.containsKey(key) -> { | |
map.remove(key) | |
map[key] = value | |
} | |
// Max capacity reached, remove the oldest item before inserting the value. | |
map.size == capacity -> { | |
val it = map.keys.iterator() | |
it.next() | |
it.remove() | |
map[key] = value | |
} | |
else -> { | |
map[key] = value | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment