大白的故事 大白的故事
首页
  • 学习笔记

    • LeetCode题解导航
  • 学习笔记

    • TypeScript笔记
页面
技术
  • 友情链接
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
dbdgs

大白的故事

终身学习者
首页
  • 学习笔记

    • LeetCode题解导航
  • 学习笔记

    • TypeScript笔记
页面
技术
  • 友情链接
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • leetcode

    • LeetCode题解
    • leetcode1 两数之和[简单难度]
    • leetcode2 Add Two Numbers
    • leetcode3 Longest Substring Without Repeating Characters
    • leetcode4 寻找两个正序数组的中位数[困难难度]
    • leetcode5 Longest Palindromic Substring
    • leetcode6 ZigZag Conversion
    • leetcode7 Reverse Integer
    • leetcode8 String to Integer (atoi)
    • leetcode9 Palindrome Number
    • leetcode10 Regular Expression Matching
    • leetcode11-盛最多水的容器[中等难度]
    • leetcode12 Integer to Roman
    • leetcode13 Roman to Integer
    • leetcode14 Longest Common Prefix
    • leetcode15 3Sum
    • leetcode16 3Sum Closest
    • leetcode17 Letter Combinations of a Phone Number
    • leetcode18 4Sum
    • leetcode19 Remove Nth Node From End of List
    • leetcode20 Valid Parentheses
    • leetcode21 Merge Two Sorted Lists
    • leetcode22 Generate Parentheses
    • leetcode23 Merge k Sorted Lists
    • leetcode24 Swap Nodes in Pairs
    • leetcode25 Reverse Nodes in k-Group
    • leetcode26 Remove Duplicates from Sorted Array
    • leetcode27 Remove Element
    • leetcode28 Implement strStr()
    • leetcode29 Divide Two Integers
    • leetcode30 Substring with Concatenation of All Words
    • leetcode31 Next Permutation
    • leetcode32 Longest Valid Parentheses
    • leetcode33 Search in Rotated Sorted Array
    • leetcode34 Find First and Last Position of Element in Sorted Array
    • leetcode35 Search Insert Position
    • leetcode36 有效的数独[中等难度]
    • leetcode37 Sudoku Solver
    • leetcode38 外观数列(报数)【中等难度】
    • leetcode39 Combination Sum
    • leetcode40 Combination Sum II
    • leetcode41 First Missing Positive-zh
    • leetcode42 Trapping Rain Water-zh
    • leetcode43 Multiply Strings-zh
    • leetcode44 Wildcard Matching-zh
    • leetcode45 Jump Game II-zh
    • leetcode46 Permutations-zh
    • leetcode47 Permutations II-zh
    • leetcode48 Rotate Image-zh
    • leetcode49 Group Anagrams-zh
    • leetcode50 Pow(x, n)-zh
    • leetcode51 N-Queens-zh
    • leetcode52 N-Queens II-zh
    • leetcode53 Maximum Subarray-zh
    • leetcode54 Spiral Matrix-zh
    • leetcode55 Jump Game-zh
    • leetcode56 Merge Intervals-zh
    • leetcode57 Insert Interval-zh
    • leetcode58 Length of Last Word-zh
    • leetcode59 Spiral Matrix II-zh
    • leetcode60 Permutation Sequence-zh
    • leetcode61 Rotate List-zh
    • leetcode62 Unique Paths-zh
    • leetcode63 Unique Paths II-zh
    • leetcode64 Minimum Path Sum-zh
    • leetcode65 Valid Number-zh
    • leetcode66 Plus One-zh
    • leetcode67 Add Binary-zh
    • leetcode68 Text Justification-zh
    • leetcode69 Sqrt(x)-zh
    • leetcode70 Climbing Stairs-zh
    • leetcode71 Simplify Path-zh
    • leetcode72 Edit Distance-zh
    • leetcode73 Set Matrix Zeroes-zh
    • leetcode74 Search a 2D Matrix-zh
    • leetcode75 Sort Colors-zh
    • leetcode76 Minimum Window Substring-zh
    • leetcode77 Combinations-zh
    • leetcode78 Subsets-zh
    • leetcode79 Word Search-zh
    • leetcode80 Remove Duplicates from Sorted Array II-zh
    • leetcode81 Search in Rotated Sorted Array II-zh
    • leetcode82 Remove Duplicates from Sorted List II-zh
    • leetcode83 Remove Duplicates from Sorted List-zh
    • leetcode84 Largest Rectangle in Histogram-zh
    • leetcode85 Maximal Rectangle-zh
    • leetcode86 Partition List-zh
    • leetcode87 Scramble String-zh
    • leetcode88 Merge Sorted Array-zh
    • leetcode89 Gray Code-zh
    • leetcode90 Subsets II-zh
    • leetcode91 Decode Ways-zh
    • leetcode92 Reverse Linked List II-zh
    • leetcode93 Restore IP Addresses-zh
    • leetcode94 Binary Tree Inorder Traversal-zh
    • leetcode95 Unique Binary Search Trees II-zh
    • leetcode96 Unique Binary Search Trees-zh
    • leetcode97 Interleaving String-zh
    • leetcode98 Validate Binary Search Tree-zh
    • leetcode99 Recover Binary Search Tree-zh
    • leetcode100 Same Tree-zh
    • leetcode101 Symmetric Tree-zh
    • leetcode102 Binary Tree Level Order Traversal-zh
    • leetcode103 Binary Tree Zigzag Level Order Traversal-zh
    • leetcode104 Maximum Depth of Binary Tree-zh
    • leetcode105 Construct Binary Tree from Preorder and Inorder Traversal-zh
    • leetcode106 Construct Binary Tree from Inorder and Postorder Traversal-zh
    • leetcode107 Binary Tree Level Order Traversal II-zh
    • leetcode108 Convert Sorted Array to Binary Search Tree-zh
    • leetcode109 Convert Sorted List to Binary Search Tree-zh
    • leetcode110 Balanced Binary Tree-zh
    • leetcode111 Minimum Depth of Binary Tree-zh
    • leetcode112 Path Sum-zh
    • leetcode113 Path Sum II-zh
    • leetcode114 Flatten Binary Tree to Linked List-zh
    • leetcode115 Distinct Subsequences-zh
    • leetcode116 Populating Next Right Pointers in Each Node-zh
    • leetcode117 Populating Next Right Pointers in Each Node II-zh
    • leetcode118 Pascal's Triangle-zh
    • leetcode119 Pascal's Triangle II-zh
    • leetcode120 Triangle-zh
    • leetcode121 Best Time to Buy and Sell Stock-zh
    • leetcode122 Best Time to Buy and Sell Stock II-zh
    • leetcode123 Best Time to Buy and Sell Stock III-zh
    • leetcode124 Binary Tree Maximum Path Sum-zh
    • leetcode125 Valid Palindrome-zh
    • leetcode126 Word Ladder II-zh
    • leetcode127 Word Ladder-zh
    • leetcode128 Longest Consecutive Sequence-zh
    • leetcode129 Sum Root to Leaf Numbers-zh
    • leetcode130 Surrounded Regions-zh
    • leetcode131 Palindrome Partitioning-zh
    • leetcode132 Palindrome Partitioning II-zh
    • leetcode133 Clone Graph-zh
    • leetcode134 Gas Station-zh
    • leetcode135 Candy-zh
    • leetcode136 Single Number-zh
    • leetcode137 Single Number II-zh
    • leetcode138 Copy List with Random Pointer-zh
    • leetcode139 Word Break-zh
    • leetcode140 Word Break II-zh
    • leetcode141 Linked List Cycle-zh
    • leetcode142 Linked List Cycle II-zh
    • leetcode143 Reorder List-zh
    • leetcode144 Binary Tree Preorder Traversal-zh
    • leetcode145 Binary Tree Postorder Traversal-zh
    • leetcode146 Lru Cache-zh
      • 题目描述
      • 解法
        • Python3
        • Java
        • ...
    • leetcode147 Insertion Sort List-zh
    • leetcode148 Sort List-zh
    • leetcode149 Max Points on a Line-zh
    • leetcode150 Evaluate Reverse Polish Notation-zh
    • leetcode151 Reverse Words in a String-zh
    • leetcode152 Maximum Product Subarray-zh
    • leetcode153 Find Minimum in Rotated Sorted Array-zh
    • leetcode154 Find Minimum in Rotated Sorted Array II-zh
    • leetcode155 Min Stack-zh
    • leetcode156 Binary Tree Upside Down-zh
    • leetcode157 Read N Characters Given Read4-zh
    • leetcode158 Read N Characters Given Read4 II - Call multiple times-zh
    • leetcode159 Longest Substring with At Most Two Distinct Characters-zh
    • leetcode160 Intersection of Two Linked Lists-zh
    • leetcode161 One Edit Distance-zh
    • leetcode162 Find Peak Element-zh
    • leetcode163 Missing Ranges-zh
    • leetcode164 Maximum Gap-zh
    • leetcode165 Compare Version Numbers-zh
    • leetcode166 Fraction to Recurring Decimal-zh
    • leetcode167 Two Sum II - Input array is sorted-zh
    • leetcode168 Excel Sheet Column Title-zh
    • leetcode169 Majority Element-zh
    • leetcode170 Two Sum III - Data structure design-zh
    • leetcode171 Excel Sheet Column Number-zh
    • leetcode172 Factorial Trailing Zeroes-zh
    • leetcode173 Binary Search Tree Iterator-zh
    • leetcode174 Dungeon Game-zh
    • leetcode175 Combine Two Tables-zh
    • leetcode176 Second Highest Salary-zh
    • leetcode177 Nth Highest Salary-zh
    • leetcode178 Rank Scores-zh
    • leetcode179 Largest Number-zh
    • leetcode180 Consecutive Numbers-zh
    • leetcode181 Employees Earning More Than Their Managers-zh
    • leetcode182 Duplicate Emails-zh
    • leetcode183 Customers Who Never Order-zh
    • leetcode184 Department Highest Salary-zh
    • leetcode185 Department Top Three Salaries-zh
    • leetcode186 Reverse Words in a String II-zh
    • leetcode187 Repeated DNA Sequences-zh
    • leetcode188 Best Time to Buy and Sell Stock IV-zh
    • leetcode189 Rotate Array-zh
    • leetcode190 Reverse Bits-zh
    • leetcode191 Number of 1 Bits-zh
    • leetcode192 Word Frequency-zh
    • leetcode193 Valid Phone Numbers-zh
    • leetcode194 Transpose File-zh
    • leetcode195 Tenth Line-zh
    • leetcode196 Delete Duplicate Emails-zh
    • leetcode197 Rising Temperature-zh
    • leetcode198 House Robber-zh
    • leetcode199 Binary Tree Right Side View-zh
    • leetcode200 Number of Islands-zh
    • leetcode201 Bitwise AND of Numbers Range-zh
    • leetcode202 Happy Number-zh
    • leetcode203 Remove Linked List Elements-zh
    • leetcode204 Count Primes-zh
    • leetcode205 Isomorphic Strings-zh
    • leetcode206 Reverse Linked List-zh
    • leetcode207 Course Schedule-zh
    • leetcode208 Implement Trie (Prefix Tree)-zh
    • leetcode209 Minimum Size Subarray Sum-zh
    • leetcode210 Course Schedule II-zh
    • leetcode211 Design Add and Search Words Data Structure-zh
    • leetcode212 Word Search II-zh
    • leetcode213 House Robber II-zh
    • leetcode214 Shortest Palindrome-zh
    • leetcode215 Kth Largest Element in an Array-zh
    • leetcode216 Combination Sum III-zh
    • leetcode217 Contains Duplicate-zh
    • leetcode218 The Skyline Problem-zh
    • leetcode219 Contains Duplicate II-zh
    • leetcode220 Contains Duplicate III-zh
    • leetcode221 Maximal Square-zh
    • leetcode222 Count Complete Tree Nodes-zh
    • leetcode223 Rectangle Area-zh
    • leetcode224 Basic Calculator-zh
    • leetcode225 Implement Stack using Queues-zh
    • leetcode226 Invert Binary Tree-zh
    • leetcode227 Basic Calculator II-zh
    • leetcode228 Summary Ranges-zh
    • leetcode229 Majority Element II-zh
    • leetcode230 Kth Smallest Element in a BST-zh
    • leetcode231 Power of Two-zh
    • leetcode232 Implement Queue using Stacks-zh
    • leetcode233 Number of Digit One-zh
    • leetcode234 Palindrome Linked List-zh
    • leetcode235 Lowest Common Ancestor of a Binary Search Tree-zh
    • leetcode236 Lowest Common Ancestor of a Binary Tree-zh
    • leetcode237 Delete Node in a Linked List-zh
    • leetcode238 Product of Array Except Self-zh
    • leetcode239 Sliding Window Maximum-zh
    • leetcode240 Search a 2D Matrix II-zh
    • leetcode241 Different Ways to Add Parentheses-zh
    • leetcode242 Valid Anagram-zh
    • leetcode243 Shortest Word Distance-zh
    • leetcode244 Shortest Word Distance II-zh
    • leetcode245 Shortest Word Distance III-zh
    • leetcode246 Strobogrammatic Number-zh
    • leetcode247 Strobogrammatic Number II-zh
    • leetcode248 Strobogrammatic Number III-zh
    • leetcode249 Group Shifted Strings-zh
    • leetcode250 Count Univalue Subtrees-zh
    • leetcode251 Flatten 2D Vector-zh
    • leetcode252 Meeting Rooms-zh
    • leetcode253 Meeting Rooms II-zh
    • leetcode254 Factor Combinations-zh
    • leetcode255 Verify Preorder Sequence in Binary Search Tree-zh
    • leetcode256 Paint House-zh
    • leetcode257 Binary Tree Paths-zh
    • leetcode258 Add Digits-zh
    • leetcode259 3Sum Smaller-zh
    • leetcode260 Single Number III-zh
  • leetcode-p2

  • 算法
  • leetcode
geekzl.com
2021-07-19

leetcode146 Lru Cache-zh

# 146. LRU 缓存机制 (opens new window)

English Version (opens new window)

# 题目描述

运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制 。

实现 LRUCache 类:

  • LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
  • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
  • void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

示例:

输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1);    // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2);    // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1);    // 返回 -1 (未找到)
lRUCache.get(3);    // 返回 3
lRUCache.get(4);    // 返回 4

提示:

  • 1 <= capacity <= 3000
  • 0 <= key <= 3000
  • 0 <= value <= 104
  • 最多调用 3 * 104 次 get 和 put

# 解法

“哈希表 + 双向链表”实现。其中:

  • 双向链表按照被使用的顺序存储 kv 键值对,靠近头部的 kv 键值对是最近使用的,而靠近尾部的键值对是最久未使用的。
  • 哈希表通过缓存的 key 映射到双向链表中的位置。我们可以在 O(1) 时间内定位到缓存的 key 所对应的 value 在链表中的位置。

对于 get 操作,判断 key 是否存在哈希表中:

  • 若不存在,返回 -1
  • 若存在,则 key 对应的节点 node 是最近使用的节点。将该节点移动到双向链表的头部,最后返回该节点的值即可。

对于 put 操作,同样先判断 key 是否存在哈希表中:

  • 若不存在,则创建一个新的 node 节点,放入哈希表中。然后在双向链表的头部添加该节点。接着判断双向链表节点数是否超过 capacity。若超过,则删除双向链表的尾部节点,以及在哈希表中对应的项。
  • 若存在,则更新 node 节点的值,然后该节点移动到双向链表的头部。

双向链表节点(哈希表的 value)的结构如下:

class Node {
	int key;
	int value;
	Node prev;
	Node next;
	Node() {

	}
	Node(int key, int value) {
		this.key = key;
		this.value = value;
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13

你可能会问,哈希表的 value 为何还要存放 key?

这是因为,双向链表有一个删除尾节点的操作。我们定位到双向链表的尾节点,在链表中删除之后,还要找到该尾节点在哈希表中的位置,因此需要根据 value 中存放的 key,定位到哈希表的数据项,然后将其删除。

# Python3

class Node:
    def __init__(self, key=0, value=0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:

    def __init__(self, capacity: int):
        self.cache = {}
        self.head = Node()
        self.tail = Node()
        self.capacity = capacity
        self.size = 0
        self.head.next = self.tail
        self.tail.prev = self.head

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self.move_to_head(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            node = self.cache[key]
            node.value = value
            self.move_to_head(node)
        else:
            node = Node(key, value)
            self.cache[key] = node
            self.add_to_head(node)
            self.size += 1
            if self.size > self.capacity:
                node = self.remove_tail()
                self.cache.pop(node.key)
                self.size -= 1
    
    def move_to_head(self, node):
        self.remove_node(node)
        self.add_to_head(node)
    
    def remove_node(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev
    
    def add_to_head(self, node):
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node
        node.prev = self.head

    def remove_tail(self):
        node = self.tail.prev
        self.remove_node(node)
        return node


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

# Java

class LRUCache {
    class Node {
        int key;
        int value;
        Node prev;
        Node next;
        Node() {

        }
        Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private Map<Integer, Node> cache;
    private Node head;
    private Node tail;
    private int capacity;
    private int size;

    public LRUCache(int capacity) {
        cache = new HashMap<>();
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        if (!cache.containsKey(key)) {
            return -1;
        }
        Node node = cache.get(key);
        moveToHead(node);
        return node.value;
    }
    
    public void put(int key, int value) {
        if (cache.containsKey(key)) {
            Node node = cache.get(key);
            node.value = value;
            moveToHead(node);
        } else {
            Node node = new Node(key, value);
            cache.put(key, node);
            addToHead(node);
            ++size;
            if (size > capacity) {
                node = removeTail();
                cache.remove(node.key);
                --size;
            }
        }
    }

    private void moveToHead(Node node) {
        removeNode(node);
        addToHead(node);
    }

    private void removeNode(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void addToHead(Node node) {
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
        node.prev = head;
    }

    private Node removeTail() {
        Node node = tail.prev;
        removeNode(node);
        return node;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

# ...


1
编辑 (opens new window)
#leetcode
上次更新: 2021/10/30, 12:58:38
leetcode145 Binary Tree Postorder Traversal-zh
leetcode147 Insertion Sort List-zh

← leetcode145 Binary Tree Postorder Traversal-zh leetcode147 Insertion Sort List-zh→

最近更新
01
leetcode2 Add Two Numbers
07-19
02
leetcode3 Longest Substring Without Repeating Characters
07-19
03
leetcode5 Longest Palindromic Substring
07-19
更多文章>
Theme by Vdoing | Copyright © 2020 大白的故事 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式