标签:imp dHash util 实现 remove lis class cap linked
第二题是实现一个lru cache , 我想到了linkedHashMap , 但是没有找到合适的api
自己撸了一个,通过了66%
1 package interview; 2 3 import java.util.HashMap; 4 import java.util.LinkedHashMap; 5 import java.util.LinkedList; 6 7 /** 8 * @program: Leetcode 9 * @description: 10 * @create: 2019-08-31 16:32 11 **/ 12 public class Sina2 { 13 14 int cap; 15 HashMap<Integer,Integer> values = new HashMap<>(); 16 HashMap<Integer,Boolean> exist = new HashMap<>(); 17 LinkedList<Integer> queue = new LinkedList<>(); 18 19 public Sina2(int capacity) { 20 this.cap = capacity; 21 } 22 23 public int get(int key) { 24 if (exist.get(key)){ 25 int temp = values.get(key); 26 queue.remove((Integer) key); 27 queue.addFirst((Integer) key); 28 System.out.println(temp); 29 return temp; 30 }else { 31 System.out.println(-1); 32 return -1; 33 } 34 } 35 36 37 public void put(int key, int value) { 38 if (queue.size() == cap){ 39 int kk = queue.get(cap-1); 40 //exist.remove(kk); 41 exist.put(kk,false); 42 values.put(key,value); 43 exist.put(key,true); 44 queue.removeLast(); 45 queue.addFirst(key); 46 }else { 47 queue.addFirst(key); 48 values.put(key,value); 49 exist.put(key,true); 50 } 51 52 } 53 54 public static void main(String[] args) { 55 Sina2 sina2 = new Sina2(2); 56 sina2.put(1,1); 57 sina2.put(2,2); 58 sina2.get(1); 59 sina2.put(3,3); 60 sina2.get(2); 61 sina2.put(4,4); 62 sina2.get(1); 63 sina2.get(3); 64 sina2.get(4); 65 66 } 67 }
标签:imp dHash util 实现 remove lis class cap linked
原文地址:https://www.cnblogs.com/vector11248/p/11439854.html