如果對于以下操作,我們都希望是O(1)的時間復雜度雪标,如何實現(xiàn):
- Insert the key
- Get the key / Check if the key exists
- Delete the key
- Return the first / or the last added key/value
前三種方式可以用HashMap來實現(xiàn),第四種方式可以用LinkedList來實現(xiàn)郊闯。
在Java中秒咨,有個類型叫LinkedHashMap,相當于HashMap + LinkedList
牡昆。LinkedHashMap 繼承了 HashMap,同時能夠做到按照插入順序或者訪問順序進行迭代孟抗。
LinkedHashMap有兩種排序方式:insertion-ordered 或者 access-order迁杨。默認是 insertion-ordered。唯一使用 access-order 的構(gòu)造方式是:
public LinkedHashMap(int initialCapacity, // 初始大小
float loadFactor, // 加載因子
boolean accessOrder) // 排序方式
涉及到的題目:
340 Longest Substring with At Most K Distinct Characters
https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
146 LRU Cache
https://leetcode.com/problems/lru-cache/