[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),当然用单向链表也可以,就是不太方便。代码如下:

class LRUCache {
    public Map<Integer, Node> map;
    public Node head;
    public Node tail;
    public int capacity;
    public int size;

    public LRUCache(int capacity) {
        map = new HashMap<>();
        head = new Node(0, 0);
        tail = new Node(0, 0);
        head.next = tail;
        tail.pre = head;

        this.capacity = capacity;
    }

    public void remove(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    public void add(Node node) {
        Node next = head.next;
        head.next = node;
        node.pre = head;
        node.next = next;
        next.pre = node;
    }
    
    public int get(int key) {
        if(map.containsKey(key)) {
            remove(map.get(key));
            add(map.get(key));
            return map.get(key).value;
        }
        return -1;
    }
    
    public void put(int key, int value) {
        if(map.containsKey(key)) {
            remove(map.get(key));
            map.remove(key);
            size--;
        }

        if(size >= capacity) {
            Node remove = tail.pre;
            remove(remove);
            map.remove(remove.key);
            size--;
        }

        Node node = new Node(key, value);
        add(node);
        map.put(key, node);
        size++;
    }
}

class Node {
    int key;
    int value;
    public Node(int key, int value) {
        this.key = key;
        this.value = value;
    }

    Node pre;
    Node next;
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

还有更简单的实现,自己构造干啥,用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/

posted @ 2018-04-08 13:00  DarrenChan陈驰  阅读(1009)  评论(0编辑  收藏  举报
Live2D