数据结构——LRU缓存、频率栈...(java)

LRU缓存

使用双向链表和hashmap构造存储key-value的LRU缓存结构

import java.util.*

public class Solution{
  //内部结点类
  public static class Node{
    int key, value;
    Node pre, next;
    
    public Node(int key, int value){
      this.key = key;
      this.value = value;
    }
  }
  
  private Map<Integer, Node> map = new HashMap<>(); //键值和LRU节点
  private Node head = new Node(-1, -1); //LRU链表头结点
  private Node tail = new Node(-1, -1); //LRU链表尾结点
  private int k; //LRU容量 

  private int get(int key){
    if(map.containsKey(key)){
      Node node = map.get(key);
      node.prev.next = node.next;
      node.next.prev = node.prev;
      moveToHead(node);
      return node.value;
    }
    return -1;
  }

  private void set(int key, int value){
    if(get(key) == -1){
      map.get(key).value = value;
    }else{
      if(map.size() == k){
        int rk = tail.prev.key;
        tail.prev.prev.next = tail;
        tail.prev = tail.prev.prev;
        map.remove(rk);
      }
      Node node = new Node(key, value);
      map.put(key, node);
      moveToHead(node);
    }
  }
  
  private void moveToHead(Node node){
    node.next = head.next;
    head.next.prev = node;
    head.next = node;
    node.prev = head;
  }

  public int[] LRU (int[][] operators, int k) {
    this.k = k;
    head.next = tail;
    tail.prev = head;
    int len = (int) Arrays.stream(operators).filter(x -> x[0]==2).count();
    int[] res = new int[len];
        
    for(int i=0, j=0; i<operators.length; i++){
      if(operators[i][0] == 1){
        set(operators[i][1], operators[i][2]);
      }else{
        res[j++] = get(operators[i][1]);
      }
    }
    return res;
  }
}

最大频率栈

class FreqStack {
    private int maxF;
    private HashMap<Integer, Integer> numsFreq = new HashMap<>();
    private HashMap<Integer, Stack<Integer>> group = new HashMap<>();

    public FreqStack() {
        maxF= 0;
    }
    
    public void push(int val) {
        int tmp = numsFreq.getOrDefault(val, 0) + 1;
        if(tmp > maxF) maxF = tmp;
        numsFreq.put(val, tmp);
        Stack<Integer> st = group.get(tmp);
        if(st != null) st.push(val);
        else {
            st = new Stack<Integer>();
            st.push(val);
            group.put(tmp, st);
        }
    }
    
    public int pop() {
        int val = group.get(maxF).pop();
        numsFreq.put(val, numsFreq.get(val)-1);
        if(group.get(maxF).size() == 0){
            --maxF;
        }
        return val;
    }
}

/**
 * Your FreqStack object will be instantiated and called as such:
 * FreqStack obj = new FreqStack();
 * obj.push(val);
 * int param_2 = obj.pop();
 */
posted @ 2021-07-27 20:34  bacmive  阅读(148)  评论(0编辑  收藏  举报