forked from algorithm004-05/algorithm004-05
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request algorithm004-05#1100 from Coword/master
320-Week 07
- Loading branch information
Showing
2 changed files
with
141 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package lesson.week.seven; | ||
|
||
import java.util.Arrays; | ||
import java.util.LinkedHashMap; | ||
import java.util.Map; | ||
|
||
/** | ||
* Created by liangwj20 on 2019/11/30 10:09 | ||
* Description: LRU缓存机制 | ||
*/ | ||
public class LeetCode_146_320 { | ||
|
||
public static void main(String[] args) { | ||
LRUCache cache = new LRUCache(2); | ||
cache.put(1, 1); | ||
cache.put(2, 2); | ||
System.out.println(cache.get(1)); | ||
cache.put(3, 3); | ||
System.out.println(cache.get(2)); | ||
|
||
} | ||
|
||
static class LRUCache extends LinkedHashMap<Integer, Integer> { | ||
|
||
private int capacity; | ||
|
||
public LRUCache(int capacity) { | ||
super(capacity, 0.75F, true); | ||
this.capacity = capacity; | ||
} | ||
|
||
public int get(int key) { | ||
return super.getOrDefault(key, -1); | ||
} | ||
|
||
public void put(int key, int value) { | ||
super.put(key, value); | ||
} | ||
|
||
@Override | ||
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { | ||
return size() > capacity; | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters