Niuke.com, design LRU cache structure

Title description

About LRU algorithm and LFU algorithm:
Know: LRU cache structure

Insert picture description here

Solution

Use the built-in data: LinkedHashMap, which consists of a hashmap and a linked list, and the linked list is responsible for maintaining the most frequently used and least used data. The linked list is a doubly linked list, and the head node and tail node can be quickly removed. At the same time, the linked list must also store the key-val, so that when deleting it, the key of the deleted node is obtained, and the key is removed from the map.

import java.util.*;

public class Solution {
    
    
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
    
    
        // write code here
        LinkedHashMap<Integer,Integer> lruMap = new LinkedHashMap<Integer,Integer>();
        ArrayList<Integer> result = new ArrayList();
        
        for(int[] opat:operators){
    
    
            int key = opat[1];
            switch(opat[0]){
    
    
                case 1:
                    int value = opat[2];
                    if(lruMap.size()<k){
    
    
                        lruMap.put(key,value);
                    }else{
    
    
                        Iterator ot = lruMap.keySet().iterator();
                        lruMap.remove(ot.next());//移除最不长使用的
                        lruMap.put(key,value);//添加,头插法
                    }
                    break;
                case 2:
                    if(lruMap.containsKey(key)){
    
    
                        int val = lruMap.get(key);
                        result.add(val);
                        lruMap.remove(key);//因为这个时候key使用了,变为最常使用了
                        lruMap.put(key,val);//添加到头
                    }else{
    
    
                        result.add(-1);
                    }
                    break;
                default:
            }
        }
        int[] resultArr = new int[result.size()];
            int i=0;
            for(int a:result){
    
    
                resultArr[i++]=a;
            }
        return resultArr;
    }
}

Guess you like

Origin blog.csdn.net/qq_44861675/article/details/114849887