• leetcode 146. LRU Cache ----- java


    esign and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

    get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
    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.

    第一次遇到的设计的题目

    其实就是简单实现LRU即Least Recently Used 近期最少使用算法。

    1、使用了HashMap和ArrayList

    public class LRUCache {
        
        int size,num;
        List<Integer> list ;
        Map<Integer,Integer> map;
    
        public LRUCache(int capacity) {
    
            size = capacity;
            num = 0;
            list = new ArrayList<Integer>();
            map = new HashMap<Integer,Integer>();
    
    
        }
    
        public int get(int key) {
            if( map.containsKey(key) ){
                list.remove((Integer)key);
                list.add(key);
                return map.get(key);
            }
            else
                return -1;
    
        }
    
        public void set(int key, int value) {
            
    
            
            if( map.containsKey(key) ){
                list.remove((Integer)key);
                map.put(key,value);
                list.add(key);
            }else{
                if( num == size ){
                    map.remove(list.get(0));    
                    list.remove((int)0);
                    map.put(key,value);
                    list.add(key);  
                }else{
                    map.put(key,value);
                    list.add(key);
                    num++;
                }
            }
            
            
            
    
    
        }
    }

    2、使用LinkedHashMap.

    public class LRUCache {

       int size,num; Map<Integer,Integer> map; public LRUCache(int capacity) { size = capacity; List list =new LinkedList(); map = new LinkedHashMap<Integer,Integer>(); } 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 set(int key, int value) { if( map.containsKey(key) ){ map.remove(key); map.put(key,value); }else{ if( num == size ){ int firstKey = map.keySet().iterator().next(); map.remove(firstKey); map.put(key,value); }else{ map.put(key,value); num++; } } } }

    3、可以使用双向链表实现。

  • 相关阅读:
    记一次诡异的调优
    java动态代理学习笔记
    c#反射机制学习和利用反射获取类型信息
    php开启ssl的方法
    关于java中split的使用
    c#使用反射调用类型成员示例
    C#关于反射加载的问题
    Twitter:使用Netty 4来减少GC开销
    Java中如何修改Jar中的内容
    Android中自定义视图View之---前奏篇
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6069555.html
Copyright © 2020-2023  润新知