LRU Cache leetcode java
題目:
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.
題解:
這道題是一個數據結構設計題,在leetcode裡面就這麼一道,還是挺經典的一道題,可以好好看看。
這道題要求設計實現LRU cache的資料結構,實現set和get功能。學習過作業系統的都應該知道,cache作為快取可以幫助快速存取資料,但是確定是容量較小。這道題要求實現的cache型別是LRU,LRU的基本思想就是“最近用到的資料被重用的概率比較早用到的大的多”,是一種更加高效的cache型別。
解決這道題的方法是:雙向連結串列+HashMap。
“為了能夠快速刪除最久沒有訪問的資料項和插入最新的資料項,我們將雙向連結串列連線Cache中的資料項,並且保證連結串列維持資料項從最近訪問到最舊訪問的順序
“注: 對於雙向連結串列的使用,基於兩個考慮。
首先是Cache中塊的命中可能是隨機的,和Load進來的順序無關。
其次,雙向連結串列插入、刪除很快,可以靈活的調整相互間的次序,時間複雜度為O(1)。”
解決了LRU的特性,現在考慮下演算法的時間複雜度。為了能減少整個資料結構的時間複雜度,就要減少查詢的時間複雜度,所以這裡利用HashMap來做,這樣時間蘇咋讀就是O(1)。
所以對於本題來說:
get(key): 如果cache中不存在要get的值,返回-1;如果cache中存在要找的值,返回其值並將其在原連結串列中刪除,然後將其作為頭結點。
set(key,value):當要set的key值已經存在,就更新其value, 將其在原連結串列中刪除,然後將其作為頭結點;當藥set的key值不存在,就新建一個node,如果當前len<capacity,就將其加入hashmap中,並將其作為頭結點,更新len長度,否則,刪除連結串列最後一個node,再將其放入hashmap並作為頭結點,但len不更新。
原則就是:對連結串列有訪問,就要更新連結串列順序。
程式碼如下:
1 private HashMap<Integer, DoubleLinkedListNode> map2 = new HashMap<Integer, DoubleLinkedListNode>();
3 private DoubleLinkedListNode head;
4 private DoubleLinkedListNode end;
5 private int capacity;
6 private int len;
7
8 public LRUCache(int capacity) {
9 this.capacity = capacity;
10 len = 0;
11 }
12
13 public int get(int key) {
14 if (map.containsKey(key)) {
15 DoubleLinkedListNode latest = map.get(key);
16 removeNode(latest);
17 setHead(latest);
18 return latest.val;
19 } else {
20 return -1;
21 }
22 }
23
24 public void removeNode(DoubleLinkedListNode node) {
25 DoubleLinkedListNode cur = node;
26 DoubleLinkedListNode pre = cur.pre;
27 DoubleLinkedListNode post = cur.next;
28
29 if (pre != null) {
30 pre.next = post;
31 } else {
32 head = post;
33 }
34
35 if (post != null) {
36 post.pre = pre;
37 } else {
38 end = pre;
39 }
40 }
41
42 public void setHead(DoubleLinkedListNode node) {
43 node.next = head;
44 node.pre = null;
45 if (head != null) {
46 head.pre = node;
47 }
48
49 head = node;
50 if (end == null) {
51 end = node;
52 }
53 }
54
55 public void set(int key, int value) {
56 if (map.containsKey(key)) {
57 DoubleLinkedListNode oldNode = map.get(key);
58 oldNode.val = value;
59 removeNode(oldNode);
60 setHead(oldNode);
61 } else {
62 DoubleLinkedListNode newNode =
63 new DoubleLinkedListNode(key, value);
64 if (len < capacity) {
65 setHead(newNode);
66 map.put(key, newNode);
67 len++;
68 } else {
69 map.remove(end.key);
70 end = end.pre;
71 if (end != null) {
72 end.next = null;
73 }
74
75 setHead(newNode);
76 map.put(key, newNode);
77 }
78 }
79 }
80 }
81
82 class DoubleLinkedListNode {
83 public int val;
84 public int key;
85 public DoubleLinkedListNode pre;
86 public DoubleLinkedListNode next;
87
88 public DoubleLinkedListNode(int key, int value) {
89 val = value;
90 this.key = key;
91 }
Reference:
1. http://blog.csdn.net/hexinuaa/article/details/6630384
(引號中字引自此處)
2. http://www.cnblogs.com/feiling/p/3426967.html
3. http://www.programcreek.com/2013/03/leetcode-lru-cache-java/ (程式碼參考)
相關推薦
LRU Cache leetcode java
題目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) -
[leetCode] LRU Cache (Java)
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get
[LeetCode] 146. LRU Cache java
/**146. LRU Cache * @date: 2016年10月27日 * @description: http://blog.csdn.net/sbitswc/article/details/35899935 */ private H
LeetCode 146 LRU Cache
code hash head width validate return .com opera != Design and implement a data structure for Least Recently Used (LRU) cach
leetcode LRU Cache Golang
Golan last n) ise port bool lan empty println package main import( "fmt" ) type Node struct { Key string Val string Pre *Node Nex
LeetCode 146. LRU Cache
高頻題,需要用unordered_map和list,做到O(1) 需要注意的一點是,list用了splice改變了節點的位置,但是iterator並不會失效,這也代表unordered_map不需要進行更新。(可以把iterator當成指標方便理解) class LRUCache { public
[leetcode] 146. LRU Cache
https://leetcode.com/problems/lru-cache/description/ class LRUCache { private: int _capacity; list<pair<int, int> >
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)
【leetcode】146.(Hard)LRU Cache
解題思路: 用map來記錄資料 用list陣列更新資料的使用情況 提交程式碼: class LRUCache { Map<Integer,Integer> map=new HashMap<>(); List<Integer> histor
Leetcode 146 LRU Cache(雙向連結串列+STL)
解題思路:用一個雙向連結串列,維護一個最近訪問次序,用map記錄對應key的結點指標。對於get請求,需要將當前結點移動到連結串列的頭位置;對於put操作,如果是更新,則同樣將當前結點移動到頭位置,如果不是更新,則在頭位置插入一個新結點。如果連結串列長度超過快取上限,則刪除末
【LeetCode刷題記錄】LRU Cache
題目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and
【LeetCode】LRU Cache 解題報告
題外話:才連續寫了幾篇部落格,部落格排名竟然就不再是“千里之外”了,已經進入2萬名之內了。再接再厲,加油! Design and implement a data structure for Least Recently Used (LRU) cache. It sho
[Leetcode-146] LRU Cache 最近最少使用頁面置換演算法
題目概要 AC 程式碼 0. 題目概要 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the foll
[LeetCode][Java] Subsets
sort arrays ++ lee 題意 integer sel duplicate ati 題目: Given a set of distinct integers, nums, return all possible subsets. Note: Ele
[LeetCode][Java] Remove Duplicates from Sorted List II
gin -m || 代碼 number 算法分析 add dup adding 題意: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only
[LeetCode][Java] Trapping Rain Water
這就是 enter rgb code sdn mil net line repr 題意: Given n non-negative integers representing an elevation map where the width of each bar
[LeetCode][Java] Letter Combinations of a Phone Number
article art present net pub spa line note not 題目: Given a digit string, return all possible letter combinations that the number
[LeetCode][Java] Search Insert Position
uri 一個 while mar 能夠 分析 數組 solution java 題目: Given a sorted array and a target value, return the index if the target is found. If
146. LRU Cache
logs pac ++ pri capacity private r+ csharp sha class LRUCache { class DNode{ public int val; public int key;
Reverse Nodes in k-Group LeetCode Java
eno number out etc lte sta lin time rop 描述Given a linked list, reverse the nodes of a linked list k at a time and return its modified lis