Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 7aa79e5

Browse filesBrowse files
author
applewjg
committed
LRU Cache
Change-Id: Ia0b8e682b36f8d5caace61da02757097da8111ec
1 parent 38f20e1 commit 7aa79e5
Copy full SHA for 7aa79e5

File tree

Expand file treeCollapse file tree

1 file changed

+40
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+40
-0
lines changed
Open diff view settings
Collapse file

‎LRUCache.java‎

Copy file name to clipboard
+40Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Author: King, nkuwjg@gmail.com
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.