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中的數據項,並且保證鏈表維持數據項從最近訪問到最舊訪問的順序 每次數據項被查詢到時,都將此數據項移動到鏈表頭部(O(1)的時間復雜度)。這樣,在進行過多次查找操作后,最近被使用過的內容就向鏈表的頭移動,而沒 有被使用的內容就向鏈表的后面移動。當需要替換時,鏈表最后的位置就是最近最少被使用的數據項,我們只需要將最新的數據項放在鏈表頭部,當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> map 
 2         =  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/ (代碼參考)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM