GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — JavaInterview/java/src/LeetCode/LRUCache_146.java at master · damaohongtu/JavaInterview Expand file tree/ Copy pathLRUCache_146.javaMore file actions 54 lines (50 loc) · 1.29 KB / Copy pathLRUCache_146.javaFile metadata and controls54 lines (50 loc) · 1.29 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 package LeetCode; import java.util.LinkedHashMap; import java.util.Map; /** * @Classname LRUCache_146 * @Description LRU算法的实现,输入一个容器,当超过了移除最近最少使用的, * cache.put(1, 1); * cache.put(2, 2); * 输入的key是任务的名字Map.entity * * 维护一个队列 * * * @Date 19-5-20 下午4:15 * @Created by mao<[email protected]> */ public class LRUCache_146 { Map<Integer,Integer> map = new LinkedHashMap<>(); int capacity=0; public LRUCache_146(int capacity) { this.capacity = capacity; } public int get(int key) { if(map.containsKey(key)){ int value = map.get(key); map.remove(key); map.put(key,value); return value; }else{ return -1; } } public void put(int key, int value) { if(capacity <= 0) return; if(map.containsKey(key)){ map.remove(key); map.put(key,value); return; } if(map.size() == capacity){ Map.Entry<Integer,Integer> entry = map.entrySet().iterator().next(); if(entry!=null){ map.remove(entry.getKey()); map.put(key,value); } }else{ map.put(key,value); } } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |