Niuke.com, LRU 캐시 구조 설계

제목 설명

LRU 알고리즘 및 LFU 알고리즘 정보 :
알고 : LRU 캐시 구조

여기에 사진 설명 삽입

해결책

내장 데이터 사용 : LinkedHashMap은 해시 맵과 연결 목록으로 구성되며 연결 목록은 가장 자주 사용되는 데이터와 가장 적게 사용되는 데이터를 유지 관리합니다. 연결 목록은 이중 연결 목록이며 헤드 노드와 테일 노드를 빠르게 제거 할 수 있습니다. 동시에 연결 목록은 key-val도 저장해야하므로 삭제할 때 삭제 된 노드의 키를 가져 와서 맵에서 키를 제거합니다.

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;
    }
}

추천

출처blog.csdn.net/qq_44861675/article/details/114849887