mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-07 09:54:57 +08:00
Add solution 146、460
This commit is contained in:
71
leetcode/0146.LRU-Cache/146. LRU Cache.go
Normal file
71
leetcode/0146.LRU-Cache/146. LRU Cache.go
Normal file
@ -0,0 +1,71 @@
|
||||
package leetcode
|
||||
|
||||
type LRUCache struct {
|
||||
head, tail *Node
|
||||
Keys map[int]*Node
|
||||
Cap int
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
Key, Val int
|
||||
Prev, Next *Node
|
||||
}
|
||||
|
||||
func Constructor(capacity int) LRUCache {
|
||||
return LRUCache{Keys: make(map[int]*Node), Cap: capacity}
|
||||
}
|
||||
|
||||
func (this *LRUCache) Get(key int) int {
|
||||
if node, ok := this.Keys[key]; ok {
|
||||
this.Remove(node)
|
||||
this.Add(node)
|
||||
return node.Val
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func (this *LRUCache) Put(key int, value int) {
|
||||
if node, ok := this.Keys[key]; ok {
|
||||
node.Val = value
|
||||
this.Remove(node)
|
||||
this.Add(node)
|
||||
return
|
||||
} else {
|
||||
node = &Node{Key: key, Val: value}
|
||||
this.Keys[key] = node
|
||||
this.Add(node)
|
||||
}
|
||||
if len(this.Keys) > this.Cap {
|
||||
delete(this.Keys, this.tail.Key)
|
||||
this.Remove(this.tail)
|
||||
}
|
||||
}
|
||||
|
||||
func (this *LRUCache) Add(node *Node) {
|
||||
node.Prev = nil
|
||||
node.Next = this.head
|
||||
if this.head != nil {
|
||||
this.head.Prev = node
|
||||
}
|
||||
this.head = node
|
||||
if this.tail == nil {
|
||||
this.tail = node
|
||||
this.tail.Next = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (this *LRUCache) Remove(node *Node) {
|
||||
if node == this.head {
|
||||
this.head = node.Next
|
||||
node.Next = nil
|
||||
return
|
||||
}
|
||||
if node == this.tail {
|
||||
this.tail = node.Prev
|
||||
node.Prev.Next = nil
|
||||
node.Prev = nil
|
||||
return
|
||||
}
|
||||
node.Prev.Next = node.Next
|
||||
node.Next.Prev = node.Prev
|
||||
}
|
40
leetcode/0146.LRU-Cache/146. LRU Cache_test.go
Normal file
40
leetcode/0146.LRU-Cache/146. LRU Cache_test.go
Normal file
@ -0,0 +1,40 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Problem147(t *testing.T) {
|
||||
obj := Constructor(2)
|
||||
fmt.Printf("obj = %v\n", MList2Ints(&obj))
|
||||
obj.Put(1, 1)
|
||||
fmt.Printf("obj = %v\n", MList2Ints(&obj))
|
||||
obj.Put(2, 2)
|
||||
fmt.Printf("obj = %v\n", MList2Ints(&obj))
|
||||
param1 := obj.Get(1)
|
||||
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
|
||||
obj.Put(3, 3)
|
||||
fmt.Printf("obj = %v\n", MList2Ints(&obj))
|
||||
param1 = obj.Get(2)
|
||||
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
|
||||
obj.Put(4, 4)
|
||||
fmt.Printf("obj = %v\n", MList2Ints(&obj))
|
||||
param1 = obj.Get(1)
|
||||
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
|
||||
param1 = obj.Get(3)
|
||||
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
|
||||
param1 = obj.Get(4)
|
||||
fmt.Printf("param_1 = %v obj = %v\n", param1, MList2Ints(&obj))
|
||||
}
|
||||
|
||||
func MList2Ints(lru *LRUCache) [][]int {
|
||||
res := [][]int{}
|
||||
head := lru.head
|
||||
for head != nil {
|
||||
tmp := []int{head.Key, head.Val}
|
||||
res = append(res, tmp)
|
||||
head = head.Next
|
||||
}
|
||||
return res
|
||||
}
|
134
leetcode/0146.LRU-Cache/README.md
Normal file
134
leetcode/0146.LRU-Cache/README.md
Normal file
@ -0,0 +1,134 @@
|
||||
# [146. LRU Cache](https://leetcode.com/problems/lru-cache/)
|
||||
|
||||
## 题目
|
||||
|
||||
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
|
||||
|
||||
Implement the `LRUCache` class:
|
||||
|
||||
- `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
|
||||
- `int get(int key)` Return the value of the `key` if the key exists, otherwise return `1`.
|
||||
- `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
|
||||
|
||||
**Follow up:**Could you do `get` and `put` in `O(1)` time complexity?
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input
|
||||
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
|
||||
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
|
||||
Output
|
||||
[null, null, null, 1, null, -1, null, -1, 3, 4]
|
||||
|
||||
Explanation
|
||||
LRUCache lRUCache = new LRUCache(2);
|
||||
lRUCache.put(1, 1); // cache is {1=1}
|
||||
lRUCache.put(2, 2); // cache is {1=1, 2=2}
|
||||
lRUCache.get(1); // return 1
|
||||
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
|
||||
lRUCache.get(2); // returns -1 (not found)
|
||||
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
|
||||
lRUCache.get(1); // return -1 (not found)
|
||||
lRUCache.get(3); // return 3
|
||||
lRUCache.get(4); // return 4
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `1 <= capacity <= 3000`
|
||||
- `0 <= key <= 3000`
|
||||
- `0 <= value <= 104`
|
||||
- At most `3 * 104` calls will be made to `get` and `put`.
|
||||
|
||||
## 题目大意
|
||||
|
||||
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
|
||||
实现 LRUCache 类:
|
||||
|
||||
- LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
|
||||
- int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
|
||||
- void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
|
||||
|
||||
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 这一题是 LRU 经典面试题,详细解释见第三章模板。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
type LRUCache struct {
|
||||
head, tail *Node
|
||||
Keys map[int]*Node
|
||||
Cap int
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
Key, Val int
|
||||
Prev, Next *Node
|
||||
}
|
||||
|
||||
func Constructor(capacity int) LRUCache {
|
||||
return LRUCache{Keys: make(map[int]*Node), Cap: capacity}
|
||||
}
|
||||
|
||||
func (this *LRUCache) Get(key int) int {
|
||||
if node, ok := this.Keys[key]; ok {
|
||||
this.Remove(node)
|
||||
this.Add(node)
|
||||
return node.Val
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func (this *LRUCache) Put(key int, value int) {
|
||||
if node, ok := this.Keys[key]; ok {
|
||||
node.Val = value
|
||||
this.Remove(node)
|
||||
this.Add(node)
|
||||
return
|
||||
} else {
|
||||
node = &Node{Key: key, Val: value}
|
||||
this.Keys[key] = node
|
||||
this.Add(node)
|
||||
}
|
||||
if len(this.Keys) > this.Cap {
|
||||
delete(this.Keys, this.tail.Key)
|
||||
this.Remove(this.tail)
|
||||
}
|
||||
}
|
||||
|
||||
func (this *LRUCache) Add(node *Node) {
|
||||
node.Prev = nil
|
||||
node.Next = this.head
|
||||
if this.head != nil {
|
||||
this.head.Prev = node
|
||||
}
|
||||
this.head = node
|
||||
if this.tail == nil {
|
||||
this.tail = node
|
||||
this.tail.Next = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (this *LRUCache) Remove(node *Node) {
|
||||
if node == this.head {
|
||||
this.head = node.Next
|
||||
node.Next = nil
|
||||
return
|
||||
}
|
||||
if node == this.tail {
|
||||
this.tail = node.Prev
|
||||
node.Prev.Next = nil
|
||||
node.Prev = nil
|
||||
return
|
||||
}
|
||||
node.Prev.Next = node.Next
|
||||
node.Next.Prev = node.Prev
|
||||
}
|
||||
```
|
74
leetcode/0460.LFU-Cache/460. LFU Cache.go
Normal file
74
leetcode/0460.LFU-Cache/460. LFU Cache.go
Normal file
@ -0,0 +1,74 @@
|
||||
package leetcode
|
||||
|
||||
import "container/list"
|
||||
|
||||
type LFUCache struct {
|
||||
nodes map[int]*list.Element
|
||||
lists map[int]*list.List
|
||||
capacity int
|
||||
min int
|
||||
}
|
||||
|
||||
type node struct {
|
||||
key int
|
||||
value int
|
||||
frequency int
|
||||
}
|
||||
|
||||
func Constructor(capacity int) LFUCache {
|
||||
return LFUCache{nodes: make(map[int]*list.Element),
|
||||
lists: make(map[int]*list.List),
|
||||
capacity: capacity,
|
||||
min: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (this *LFUCache) Get(key int) int {
|
||||
value, ok := this.nodes[key]
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
currentNode := value.Value.(*node)
|
||||
this.lists[currentNode.frequency].Remove(value)
|
||||
currentNode.frequency++
|
||||
if _, ok := this.lists[currentNode.frequency]; !ok {
|
||||
this.lists[currentNode.frequency] = list.New()
|
||||
}
|
||||
newList := this.lists[currentNode.frequency]
|
||||
newNode := newList.PushBack(currentNode)
|
||||
this.nodes[key] = newNode
|
||||
if currentNode.frequency-1 == this.min && this.lists[currentNode.frequency-1].Len() == 0 {
|
||||
this.min++
|
||||
}
|
||||
return currentNode.value
|
||||
}
|
||||
|
||||
func (this *LFUCache) Put(key int, value int) {
|
||||
if this.capacity == 0 {
|
||||
return
|
||||
}
|
||||
if currentValue, ok := this.nodes[key]; ok {
|
||||
currentNode := currentValue.Value.(*node)
|
||||
currentNode.value = value
|
||||
this.Get(key)
|
||||
return
|
||||
}
|
||||
if this.capacity == len(this.nodes) {
|
||||
currentList := this.lists[this.min]
|
||||
frontNode := currentList.Front()
|
||||
delete(this.nodes, frontNode.Value.(*node).key)
|
||||
currentList.Remove(frontNode)
|
||||
}
|
||||
this.min = 1
|
||||
currentNode := &node{
|
||||
key: key,
|
||||
value: value,
|
||||
frequency: 1,
|
||||
}
|
||||
if _, ok := this.lists[1]; !ok {
|
||||
this.lists[1] = list.New()
|
||||
}
|
||||
newList := this.lists[1]
|
||||
newNode := newList.PushBack(currentNode)
|
||||
this.nodes[key] = newNode
|
||||
}
|
64
leetcode/0460.LFU-Cache/460. LFU Cache_test.go
Normal file
64
leetcode/0460.LFU-Cache/460. LFU Cache_test.go
Normal file
@ -0,0 +1,64 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Problem460(t *testing.T) {
|
||||
obj := Constructor(5)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(1, 1)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(2, 2)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(3, 3)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(4, 4)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(5, 5)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
|
||||
param1 := obj.Get(4)
|
||||
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
param1 = obj.Get(4)
|
||||
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
param1 = obj.Get(4)
|
||||
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
param1 = obj.Get(5)
|
||||
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
param1 = obj.Get(5)
|
||||
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
param1 = obj.Get(5)
|
||||
fmt.Printf("param_1 = %v obj.list = %v obj.map = %v obj.min = %v\n", param1, MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(6, 6)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(7, 7)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
obj.Put(8, 8)
|
||||
fmt.Printf("obj.list = %v obj.map = %v obj.min = %v\n", MLists2Ints(&obj), MList2Ints(&obj), obj.min)
|
||||
}
|
||||
|
||||
func MList2Ints(lfu *LFUCache) map[int][][]int {
|
||||
res := map[int][][]int{}
|
||||
for k, v := range lfu.nodes {
|
||||
node := v.Value.(*node)
|
||||
arr := [][]int{}
|
||||
tmp := []int{node.key, node.value, node.frequency}
|
||||
arr = append(arr, tmp)
|
||||
res[k] = arr
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func MLists2Ints(lfu *LFUCache) map[int][]int {
|
||||
res := map[int][]int{}
|
||||
for k, v := range lfu.lists {
|
||||
tmp := []int{}
|
||||
for head := v.Front(); head != nil; head = head.Next() {
|
||||
tmp = append(tmp, head.Value.(*node).value)
|
||||
}
|
||||
res[k] = tmp
|
||||
}
|
||||
return res
|
||||
}
|
142
leetcode/0460.LFU-Cache/README.md
Normal file
142
leetcode/0460.LFU-Cache/README.md
Normal file
@ -0,0 +1,142 @@
|
||||
# [460. LFU Cache](https://leetcode.com/problems/lfu-cache/)
|
||||
|
||||
|
||||
## 题目
|
||||
|
||||
Design and implement a data structure for [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache.
|
||||
|
||||
Implement the `LFUCache` class:
|
||||
|
||||
- `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure.
|
||||
- `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `1`.
|
||||
- `void put(int key, int value)` Sets or inserts the value if the `key` is not already present. When the cache reaches its `capacity`, it should invalidate the least frequently used item before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), **the least recently** used `key` would be evicted.
|
||||
|
||||
**Notice that** the number of times an item is used is the number of calls to the `get` and `put` functions for that item since it was inserted. This number is set to zero when the item is removed.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```
|
||||
Input
|
||||
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
|
||||
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
|
||||
Output
|
||||
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
|
||||
|
||||
Explanation
|
||||
LFUCache lfu = new LFUCache(2);
|
||||
lfu.put(1, 1);
|
||||
lfu.put(2, 2);
|
||||
lfu.get(1); // return 1
|
||||
lfu.put(3, 3); // evicts key 2
|
||||
lfu.get(2); // return -1 (not found)
|
||||
lfu.get(3); // return 3
|
||||
lfu.put(4, 4); // evicts key 1.
|
||||
lfu.get(1); // return -1 (not found)
|
||||
lfu.get(3); // return 3
|
||||
lfu.get(4); // return 4
|
||||
|
||||
```
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- `0 <= capacity, key, value <= 104`
|
||||
- At most `10^5` calls will be made to `get` and `put`.
|
||||
|
||||
**Follow up:** Could you do both operations in `O(1)` time complexity?
|
||||
|
||||
## 题目大意
|
||||
|
||||
请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。
|
||||
|
||||
实现 LFUCache 类:
|
||||
|
||||
- LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象
|
||||
- int get(int key) - 如果键存在于缓存中,则获取键的值,否则返回 -1。
|
||||
- void put(int key, int value) - 如果键已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最久未使用 的键。
|
||||
|
||||
注意「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
|
||||
|
||||
进阶:你是否可以在 O(1) 时间复杂度内执行两项操作?
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 这一题是 LFU 经典面试题,详细解释见第三章模板。
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
package leetcode
|
||||
|
||||
import "container/list"
|
||||
|
||||
type LFUCache struct {
|
||||
nodes map[int]*list.Element
|
||||
lists map[int]*list.List
|
||||
capacity int
|
||||
min int
|
||||
}
|
||||
|
||||
type node struct {
|
||||
key int
|
||||
value int
|
||||
frequency int
|
||||
}
|
||||
|
||||
func Constructor(capacity int) LFUCache {
|
||||
return LFUCache{nodes: make(map[int]*list.Element),
|
||||
lists: make(map[int]*list.List),
|
||||
capacity: capacity,
|
||||
min: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (this *LFUCache) Get(key int) int {
|
||||
value, ok := this.nodes[key]
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
currentNode := value.Value.(*node)
|
||||
this.lists[currentNode.frequency].Remove(value)
|
||||
currentNode.frequency++
|
||||
if _, ok := this.lists[currentNode.frequency]; !ok {
|
||||
this.lists[currentNode.frequency] = list.New()
|
||||
}
|
||||
newList := this.lists[currentNode.frequency]
|
||||
newNode := newList.PushBack(currentNode)
|
||||
this.nodes[key] = newNode
|
||||
if currentNode.frequency-1 == this.min && this.lists[currentNode.frequency-1].Len() == 0 {
|
||||
this.min++
|
||||
}
|
||||
return currentNode.value
|
||||
}
|
||||
|
||||
func (this *LFUCache) Put(key int, value int) {
|
||||
if this.capacity == 0 {
|
||||
return
|
||||
}
|
||||
if currentValue, ok := this.nodes[key]; ok {
|
||||
currentNode := currentValue.Value.(*node)
|
||||
currentNode.value = value
|
||||
this.Get(key)
|
||||
return
|
||||
}
|
||||
if this.capacity == len(this.nodes) {
|
||||
currentList := this.lists[this.min]
|
||||
frontNode := currentList.Front()
|
||||
delete(this.nodes, frontNode.Value.(*node).key)
|
||||
currentList.Remove(frontNode)
|
||||
}
|
||||
this.min = 1
|
||||
currentNode := &node{
|
||||
key: key,
|
||||
value: value,
|
||||
frequency: 1,
|
||||
}
|
||||
if _, ok := this.lists[1]; !ok {
|
||||
this.lists[1] = list.New()
|
||||
}
|
||||
newList := this.lists[1]
|
||||
newNode := newList.PushBack(currentNode)
|
||||
this.nodes[key] = newNode
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user