【leetcode刷题笔记】LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.



题解:用双向链表实现一个LRU cache,这里自定义越靠近链表头的node,在越近的时间使用过。支持两个操作——get和set:

  1. get(key):如果链表中有key对应的node,返回该node的值,并把node移到链表头部(最近使用过);如果没有,返回-1;
  2. set(key,value):如果链表中已经有key对应的node,修改对应node的值为value(但不需要把这个node放在头结点处);如果链表中没有key对应的node,那么要新建node插入链表中,但此时要看链表是否还有空间。如果没有,就将尾部node(最少使用的node)删除,然后在头部插入新的node。

为了提高查找效率,这里使用一个hashMap存放<key,node>键值对,这样就可以在O(1)的时间判断cache中是否存在对应的key。

代码如下:

 1 public class LRUCache {
 2     private class Node{
 3         int value;
 4         int key;
 5         Node before;
 6         Node after;
 7         public Node(int key,int value){
 8             this.value = value;
 9             this.key = key;
10             before = null;
11             after = null;
12         }
13     }
14
15     private int capacity;
16     private HashMap<Integer, Node> map = new HashMap<Integer,Node>();
17     private Node headNode = new Node(-1, -1);
18     private Node tailNode = new Node(-1, -1);
19
20     public LRUCache(int capacity) {
21         this.capacity = capacity;
22         headNode.after = tailNode;
23         tailNode.before = headNode;
24     }
25
26     public void move_to_head(Node current){
27         current.after = headNode.after;
28         headNode.after = current;
29         current.before = headNode;
30         current.after.before = current;
31     }
32     public int get(int key) {
33         //if we don‘t have this node
34         if(!map.containsKey(key))
35             return -1;
36
37         //if we have this node, get it and move it to head
38         Node current = map.get(key);
39         current.before.after = current.after;
40         current.after.before = current.before;
41         move_to_head(current);
42
43         return map.get(key).value;
44     }
45
46     public void set(int key, int value) {
47         //if we already have this node,just change its value
48         if(get(key) != -1){
49             map.get(key).value = value;
50             return;
51         }
52
53         //if we indeed don‘t have this node, we first check capacity
54         if(map.size() == capacity){
55             map.remove(tailNode.before.key);
56             tailNode.before.before.after = tailNode;
57             tailNode.before = tailNode.before.before;
58         }
59
60         //now we are sure we have space for this new node,put it ahead of the list
61         Node newNode = new Node(key, value);
62         map.put(key, newNode);
63         move_to_head(newNode);
64     }
65 }

在实现的时候,还设置了两个node:head和tail,真正的cache数据节点存放在二者之间。

【leetcode刷题笔记】LRU Cache

时间: 2024-10-06 05:08:36

【leetcode刷题笔记】LRU Cache的相关文章

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的

【leetcode刷题笔记】Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 题解:因为题目要求原地算法,所以我们只能利用矩阵第一行和第一列存放置零信息. 首先遍历第一行和第一列,看他们是否需要全部置零,用两个变量first_column_zero和first_row_zero来记录: 遍历矩阵,如果某个位置matrix[i][j]出现了0,就把matrix[i][0]和Matrix[0