zoukankan      html  css  js  c++  java
  • [LeetCode]146.LRU缓存机制

    设计和实现一个 LRU(最近最少使用)缓存 数据结构,使它应该支持以下操作: get 和 put 。

    get(key) - 如果密钥存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
    put(key, value) - 如果密钥不存在,请设置或插入值。当缓存达到其容量时,它应该在插入新项目之前使最近最少使用的项目作废。

    后续:

    你是否可以在 O(1) 时间复杂度中进行两种操作?注:这道题也是2018今日头条春招面试题。

    案例:

    LRUCache cache = new LRUCache( 2 /* 容量 */ );
    
    cache.put(1, 1);
    cache.put(2, 2);
    cache.get(1);       // 返回  1
    cache.put(3, 3);    // 该操作,会将 key 2 作废
    cache.get(2);       // 返回 -1 (结果不存在)
    cache.put(4, 4);    // 该操作,会将 key 1 作废
    cache.get(1);       // 返回 -1 (结果不存在)
    cache.get(3);       // 返回  3
    cache.get(4);       // 返回  4

    求解思路:其实这道题并不难,就是找一个合适的数据结构去存储,每次get之后,要把get到的数提前到最前面,如果没有get到,则返回-1。put的时候,先查看有没有相同的key元素,有的话,直接把那个删掉,否则不做处理。然后判断当前的元素个数是否小于capacity,小于的话就在最前面添加新元素即可,否则在最前面添加新元素之后,还要把最后面的元素删掉。

    思路简单,难的是时间复杂度,我最开始直接想的是利用现成的数据结构,就用的是Java中的LinkedList和HashMap,HashMap中存储的是key和value,LinkedList中存储的是若干个map。代码如下:

    package com.darrenchan.dp;
    
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    
    class LRUCache2 {
        
        public int capacity;
        public List<Map<Integer, Integer>> list = new LinkedList<>();
        
        public LRUCache2(int capacity) {
            this.capacity = capacity;
        }
        
        public int get(int key) {
            int value = -1;
            for (Map<Integer, Integer> map : list) {
                if(map.get(key) != null){
                    value = map.get(key);
                    list.remove(map);
                    list.add(0, map);
                    break;
                }
            }
            return value;
        }
        
        public void put(int key, int value) {
            int index = -1;
            for (Map<Integer, Integer> map : list) {
                if(map.get(key) != null){
                    list.remove(map);
                    break;
                }
            }
            int size = list.size();
            Map<Integer, Integer> map = new HashMap<>();
            map.put(key, value);
            if(size < capacity){
                list.add(0, map);
            }else{
                list.add(0, map);
                list.remove(capacity);
            }
        }
        
        public static void main(String[] args) {
            LRUCache2 lruCache = new LRUCache2(2);
            System.out.println(lruCache.get(2));
            lruCache.put(2, 6);
            System.out.println(lruCache.get(1));
            lruCache.put(1, 5);
            lruCache.put(1, 2);
            System.out.println(lruCache.get(1));
            System.out.println(lruCache.get(2));
        }
    }

    这样时间复杂度是O(N),因为每次需要for循环,时间超时。看来不能用现成的了,需要自己构造一个数据结构,这里采用双向链表和HashMap的结构,HashMap中存储的是key和Node,Node中存储的是key和value。HashMap能保证查找的时间复杂度是O(1),双向链表保证的是增删的时间复杂度是O(1),当然用单向链表也可以,就是不太方便。代码如下:

    package com.darrenchan.dp;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    
    class LRUCache3 {
        
        public int capacity;
        public Map<Integer, Node> map;
        public Node head;//设一个虚拟的头结点
        public Node tail;//设一个虚拟的尾结点
        public int size;//链表长度
        
        public LRUCache3(int capacity) {
            this.capacity = capacity;
            this.map = new HashMap<>();
            head = new Node(0, 0);
            tail = new Node(0, 0);
            
            head.pre = null;
            head.next = tail;
            tail.pre = head;
            tail.next = null;
        }
        
        public void removeNode(Node node){
            node.pre.next = node.next;
            node.next.pre = node.pre;
        }
        
        public void addToHead(Node node){
            node.next = head.next;
            node.next.pre = node;
            node.pre = head;
            head.next = node;
        }
        
        public int get(int key) {
            int value = -1;
            if(map.get(key) != null){
                value = map.get(key).value;
                removeNode(map.get(key));
                addToHead(map.get(key));
            }
            return value;
        }
        
        public void put(int key, int value) {
            if(map.get(key) != null){
                removeNode(map.get(key));
                map.remove(key);
                size--;
            }
            Node node = new Node(key, value);
            map.put(key, node);
            if(size < capacity){
                addToHead(node);
                size++;
            }else{
                Node remove = tail.pre;
                removeNode(remove);
                map.remove(remove.key);
                addToHead(node);
            }
        }
        
        public static void main(String[] args) {
            LRUCache3 lruCache = new LRUCache3(2);
            System.out.println(lruCache.get(2));
            lruCache.put(2, 6);
            System.out.println(lruCache.get(1));
            lruCache.put(1, 5);
            lruCache.put(1, 2);
            System.out.println(lruCache.get(1));
            System.out.println(lruCache.get(2));
        }
    }
    
    class Node{
        int key;
        int value;
        public Node(int key, int value) {
            super();
            this.key = key;
            this.value = value;
        }
        Node pre;
        Node next;
    }

    还有更简单的实现,自己构造干啥,用Java现成的数据结构啊,LinkedHashMap不就是这样的吗?时间复杂度为O(1)。

    直接上代码:

    package com.darrenchan.dp;
    
    import java.util.LinkedHashMap;
    
    class LRUCache4 {
        
        public int capacity;
        public LinkedHashMap<Integer, Integer> map;
        
        public LRUCache4(int capacity) {
            this.capacity = capacity;
            map = new LinkedHashMap<>();
        }
        
        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(map.containsKey(key)){
                map.remove(key);
            }
            if(map.size() >= capacity){
                map.remove(map.keySet().iterator().next());
            }
            map.put(key, value);
        }
        
        public static void main(String[] args) {
            LRUCache4 lruCache = new LRUCache4(2);
            System.out.println(lruCache.get(2));
            lruCache.put(2, 6);
            System.out.println(lruCache.get(1));
            lruCache.put(1, 5);
            lruCache.put(1, 2);
            System.out.println(lruCache.get(1));
            System.out.println(lruCache.get(2));
        }
    }

    原题链接:https://leetcode-cn.com/problems/lru-cache/description/

  • 相关阅读:
    python-创建一个登录判断的函数
    python-创建一个本地txt文本
    python-简单函数小例子 单位转换
    微信小程序性能测试之jmeter踩坑记录(四)
    手动添加Keil的固件包Packs
    使用Socket的简单Web服务器
    网络端口(port)
    Redis 5种主要数据类型和命令
    c# 索引器方法
    .net 获取类型的Type类型的几种方法
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/8744354.html
Copyright © 2011-2022 走看看