Skip to content

Commit 7aa79e5

Browse files
author
applewjg
committed
LRU Cache
Change-Id: Ia0b8e682b36f8d5caace61da02757097da8111ec
1 parent 38f20e1 commit 7aa79e5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

LRUCache.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: March 12, 2014
4+
Problem: LRU Cache
5+
Difficulty: Hard
6+
Source: http://oj.leetcode.com/problems/lru-cache/
7+
Notes:
8+
Design and implement a data structure for Least Recently Used (LRU) cache.
9+
It should support the following operations: get and set.
10+
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
11+
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.
12+
13+
Solution: Hash + list.
14+
*/
15+
16+
import java.util.LinkedHashMap;
17+
import java.util.Map;
18+
public class LRUCache {
19+
private Map<Integer, Integer> map;
20+
private int capacity;
21+
public LRUCache(int capacity) {
22+
this.capacity = capacity;
23+
map = new LinkedHashMap<Integer, Integer>(capacity);
24+
}
25+
26+
public int get(int key) {
27+
Integer val = map.get(key);
28+
if (val == null) return -1;
29+
map.remove(key);
30+
map.put(key, val);
31+
return val;
32+
}
33+
34+
public void set(int key, int value) {
35+
map.remove(key);
36+
map.put(key, value);
37+
if (map.size() > capacity)
38+
map.remove(map.entrySet().iterator().next().getKey());
39+
}
40+
}

0 commit comments

Comments
 (0)