Study Notes
  • Kuma Blog
  • AI
    • AI-Resources
    • AI-books
    • Prompts
      • Prompts Free Courses
  • Movies
    • 2024
    • 2024
    • 2024
  • Google
    • chunked-palindrome
  • Setup
    • How to add a new user into Ubuntu and setup ssh key?
    • How to set up VSCode remote server connect with browser with Docker
  • kubernetes
  • Books
    • Designing-Data-Intensive-Applications
      • 第一章 — 可靠性,可扩展性,可维护性的应用程序(Reliable, Scalable, and Maintainable Applications)
    • System-Performance
      • Design-Data-Intensive-Application
      • Chapter 2: Methodologies
  • Languages
    • japanese
      • japanese-week
  • Leetcode
    • 30DayChallenge
      • LRU-cache
      • backspace-string-compare
      • binary-tree-maximum-path-sum
      • bitwise-and-number-range
      • check-string-valid-sequence-from-root-to-leaves-path-in-bst
      • construct-binary-search-tree-from-preorder-traversal
      • contiguous-array
      • counting-elements
      • diameter-of-binary-tree
      • first-unique-number
      • group-anagrams
      • jump-game
      • last-stone-weight
      • leftmost-column-with-at-least-a-one
      • longest-common-subsequect
      • maximal-square
      • maximum-subarray
      • middle-of-the-linked-list
      • min-stack
      • minimun-path-sum
      • move-zeroes
      • perform-string-shifts
      • product-of-array-except-itself
      • search-in-rotated-sorted-array
      • subarray-sum-equals-k
      • valid-parenthesis-string
    • English Solution
      • 1168.optimize-water-distribution-in-a-village-en
      • 1171.remove-zero-sum-consecutive-nodes-from-linked-list-en
      • 1177.can-make-palindrome-from-substring-en
      • 1343.number-of-avg-subarr-sizek-greater-or-equal-threshold
      • 1345.jump-game-iv
      • 25.reverse-nodes-in-k-groups-en
      • 474.ones-and-zeros-en
      • 53.maximum-sum-subarray-en
      • 547.friend-circles-en
      • 79.word-search-en
    • May2020Challenge
      • check-if-straight-line
      • cousins-in-binary-tree
      • find-town-judge
      • first-bad-version
      • first-unique-character-in-a-string
      • flood-fill
      • implement-trie
      • jewels-and-stones
      • majority-element
      • maximum-sum-circular-subarray
      • number-complement
      • odd-even-linkedlist
      • ransom-note
      • remove-k-digits
      • single-element-in-sorted-array
      • valid-perfect-square
    • python
      • 000017-Letter-Combinations-of-a-Phone-Number
      • 000032-Longest-Valid-Parentheses
      • 000033-Search-in-Rotated-Sorted-Array
      • 000046-Permutations
      • 000074-Search-a-2D-Matrix
      • 000077-Combinations
      • 000081-Search-in-Rotated-Sorted-Array-II
      • 000137-single-number-ii
      • 000139-Word-Break
      • 000207-courses-schedule
      • 000209-Minimum-Size-Subarray-Sum
      • 000376-wiggle-subsequence
      • 000445-Add-Two-Numbers-II
      • 000486-Predict-the-Winner
      • 000518-Coin-Change-II
      • 000673-Number-of-Longest-Increasing-Subsequence
      • 000688-Knight-Probability-in-Chessboard
      • 000735-Asteroid-Collision
      • 000852-Peak-Index-in-a-Mountain-Array
      • 859-Buddy-Strings
      • 000864-Shortest-Path-to-Get-All-Keys
      • 000920-Number-of-Music-Playlists
      • 001218-Longest-Arithmetic-Subsequence-of-Given-Difference
      • 001235-Maximum-Profit-in-Job-Scheduling
      • 001493-Longest-Subarray-of 1-After-Deleting-One-Element
      • Problem
      • 002024-Maximize-the-Confusion-of-an-Exam
      • 2305-Fair-Distribution-of-Cookies
      • 002616-Minimize-the-Maximum-Difference-of-Pairs
      • 00802-Find-Eventual-Safe-States
    • 中文版解题
      • 1147.longest-chunked-palindrome-decomposition-cn
      • 1168.optimize-water-distribution-in-a-village-cn
      • 1171.remove-zero-sum-consecutive-nodes-from-linked-list-cn
      • 1177.can-make-palindrome-from-substring-cn
      • 215.kth-largest-element-in-an-array-cn
      • 25.reverse-nodes-in-k-groups-cn
      • 30.substring-with-concatenation-of-all-words-cn
      • 4.median-of-two-sorted-array-cn
      • 460.LFU-cache-cn
      • 474.ones-and-zeros-cn
      • 53.maximum-sum-subarray-cn
      • 79.word-search-cn
  • Readings
    • 2020
      • Design-Data-Intensive-Application
      • 亲爱的提奥
      • 理想国
      • 贫穷的本质
Powered by GitBook
On this page
  • 题目地址
  • 题目描述
  • 思路
  • 关键点分析
  • 代码(Java code)
  • 参考(References)

Was this helpful?

  1. Leetcode
  2. 中文版解题

460.LFU-cache-cn

Previous4.median-of-two-sorted-array-cnNext474.ones-and-zeros-cn

Last updated 5 years ago

Was this helpful?

题目地址

题目描述

Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LFUCache cache = new LFUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.get(3);       // returns 3.
cache.put(4, 4);    // evicts key 1.
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

思路

举个例子,比如说cache容量是 3,按顺序依次放入 1,2,1,2,1,3, cache已存满 3 个元素 (1,2,3), 这时如果想放入一个新的元素 4 的时候,就需要腾出一个元素空间。 用 LFU,这里就淘汰 3, 因为 3 的次数只出现依次, 1 和 2 出现的次数都比 3 多。

题中 get 和 put 都是 O(1)的时间复杂度,那么删除和增加都是O(1),可以想到用双链表,和HashMap,用一个HashMap, nodeMap, 保存当前key,和 node{key, value, frequent}的映射。 这样get(key)的操作就是O(1). 如果要删除一个元素,那么就需要另一个HashMap,freqMap,保存元素出现次数(frequent)和双链表(DoublyLinkedlist) 映射, 这里双链表存的是frequent相同的元素。每次get或put的时候,frequent+1,然后把node插入到双链表的head node, head.next=node 每次删除freqent最小的双链表的tail node, tail.prev。

用给的例子举例说明:

 1. put(1, 1), 
    - 首先查找nodeMap中有没有key=1对应的value,
        没有就新建node(key, value, freq) -> node1(1, 1, 1), 插入 nodeMap,{[1, node1]}
    - 查找freqMap中有没有freq=1 对应的value,
        没有就新建doublylinkedlist(head, tail), 把node1 插入doublylinkedlist head->next = node1.
    如下图,
 2. put(2, 2), 
    - 首先查找nodeMap中有没有key=2对应的value,
        没有就新建node(key, value, freq) -> node2(2, 2, 1), 插入 nodeMap,{[1, node1], [2, node2]}
    - 查找freqMap中有没有freq=1 对应的value,
        没有就新建doublylinkedlist(head, tail), 把node2 插入doublylinkedlist head->next = node2.
    如下图,
 3. get(1), 
    - 首先查找nodeMap中有没有key=1对应的value,nodeMap:{[1, node1], [2, node2]},
        找到node1,把node1 freq+1 -> node1(1,1,2)
    - 更新freqMap,删除freq=1,node1
    - 更新freqMap,插入freq=2,node1
    如下图,
 4. put(3, 3), 
    - 判断cache的capacity,已满,需要淘汰使用次数最少的元素,找到最小的freq=1,删除双链表tail node.prev 
        如果tailnode.prev != null, 删除。然后从nodeMap中删除对应的key。
    - 首先查找nodeMap中有没有key=3对应的value,
        没有就新建node(key, value, freq) -> node3(3, 3, 1), 插入 nodeMap,{[1, node1], [3, node3]}
    - 查找freqMap中有没有freq=1 对应的value,
        没有就新建doublylinkedlist(head, tail), 把node3 插入doublylinkedlist head->next = node3.
    如下图,
 5. get(2) 
    - 查找nodeMap,如果没有对应的key的value,返回 -1。

 6. get(3)
    - 首先查找nodeMap中有没有key=3对应的value,nodeMap:{[1, node1], [3, node3]},
        找到node3,把node3 freq+1 -> node3(3,3,2)
    - 更新freqMap,删除freq=1,node3
    - 更新freqMap,插入freq=2,node3
    如下图,
 7. put(4, 4), 
    - 判断cache的capacity,已满,需要淘汰使用次数最少的元素,找到最小的freq=1,删除双链表tail node.prev 
        如果tailnode.prev != null, 删除。然后从nodeMap中删除对应的key。
    - 首先查找nodeMap中有没有key=4对应的value,
        没有就新建node(key, value, freq) -> node4(4, 4, 1), 插入 nodeMap,{[4, node4], [3, node3]}
    - 查找freqMap中有没有freq=1 对应的value,
        没有就新建doublylinkedlist(head, tail), 把 node4 插入doublylinkedlist head->next = node4.
    如下图,
 8. get(1) 
    - 查找nodeMap,如果没有对应的key的value,返回 -1。

 9. get(3)
    - 首先查找nodeMap中有没有key=3对应的value,nodeMap:{[4, node4], [3, node3]},
        找到node3,把node3 freq+1 -> node3(3,3,3)
    - 更新freqMap,删除freq=2,node3
    - 更新freqMap,插入freq=3,node3
    如下图,
 10. get(4)
    - 首先查找nodeMap中有没有key=4对应的value,nodeMap:{[4, node4], [3, node3]},
        找到node4,把node4 freq+1 -> node4(4,4,2)
    - 更新freqMap,删除freq=1,node4
    - 更新freqMap,插入freq=2,node4
    如下图,

关键点分析

用两个Map分别保存 nodeMap {key, node} 和 freqMap{frequent, DoublyLinkedList}。 实现get 和 put操作都是O(1)的时间复杂度。

可以用Java自带的一些数据结构,比如HashLinkedHashSet,这样就不需要自己自建Node,DoublelyLinkedList。 可以很大程度的缩减代码量。

代码(Java code)

public class LC460LFUCache {
  class Node {
    int key, val, freq;
    Node prev, next;

    Node(int key, int val) {
      this.key = key;
      this.val = val;
      freq = 1;
    }
  }

  class DoubleLinkedList {
    private Node head;
    private Node tail;
    private int size;

    DoubleLinkedList() {
      head = new Node(0, 0);
      tail = new Node(0, 0);
      head.next = tail;
      tail.prev = head;
    }

    void add(Node node) {
      head.next.prev = node;
      node.next = head.next;
      node.prev = head;
      head.next = node;
      size++;
    }

    void remove(Node node) {
      node.prev.next = node.next;
      node.next.prev = node.prev;
      size--;
    }

    // always remove last node if last node exists
    Node removeLast() {
      if (size > 0) {
        Node node = tail.prev;
        remove(node);
        return node;
      } else return null;
    }
  }

  // cache capacity
  private int capacity;
  // min frequent
  private int minFreq;
  Map<Integer, Node> nodeMap;
  Map<Integer, DoubleLinkedList> freqMap;
  public LC460LFUCache(int capacity) {
    this.minFreq = 0;
    this.capacity = capacity;
    nodeMap = new HashMap<>();
    freqMap = new HashMap<>();
  }

  public int get(int key) {
    Node node = nodeMap.get(key);
    if (node == null) return -1;
    update(node);
    return node.val;
  }

  public void put(int key, int value) {
    if (capacity == 0) return;
    Node node;
    if (nodeMap.containsKey(key)) {
      node = nodeMap.get(key);
      node.val = value;
      update(node);
    } else {
      node = new Node(key, value);
      nodeMap.put(key, node);
      if (nodeMap.size() == capacity) {
        DoubleLinkedList lastList = freqMap.get(minFreq);
        nodeMap.remove(lastList.removeLast().key);
      }
      minFreq = 1;
      DoubleLinkedList newList = freqMap.getOrDefault(node.freq, new DoubleLinkedList());
      newList.add(node);
      freqMap.put(node.freq, newList);
    }
  }

  private void update(Node node) {
    DoubleLinkedList oldList = freqMap.get(node.freq);
    oldList.remove(node);
    if (node.freq == minFreq && oldList.size == 0) minFreq++;
    node.freq++;
    DoubleLinkedList newList = freqMap.getOrDefault(node.freq, new DoubleLinkedList());
    newList.add(node);
    freqMap.put(node.freq, newList);
  }
 }

参考(References)

但内存容量满的情况下,有新的数据进来,需要更多空间的时候,就需要删除被访问频率最少的元素。

[Leetcode discussion mylzsd]()

[Leetcode discussion aaaeeeo]()

Problem
LFU(Least frequently used)
LFU(Least frequently used) Cache
https://leetcode.com/problems/lfu-cache/discuss/94547/Java-O(1)-Solution-Using-Two-HashMap-and-One-DoubleLinkedList
https://leetcode.com/problems/lfu-cache/discuss/94547/Java-O(1)-Solution-Using-Two-HashMap-and-One-DoubleLinkedList
460.lfu-cache-1
460.lfu-cache-2
460.lfu-cache-3
460.lfu-cache-4
460.lfu-cache-5
460.lfu-cache-6
460.lfu-cache-7
460.lfu-cache-8