Skip to content

add: leetcode - 460 lfu cache#81

Open
kwonyg wants to merge 1 commit into
Devrother:masterfrom
kwonyg:master
Open

add: leetcode - 460 lfu cache#81
kwonyg wants to merge 1 commit into
Devrother:masterfrom
kwonyg:master

Conversation

@kwonyg

@kwonyg kwonyg commented Apr 22, 2020

Copy link
Copy Markdown
Member

leetcode - 460 lfu cache(#76 )

LFU cache

운영체제 기준, 어떤 블록이 메모리에서 참조된 횟수를 관리한다. 캐시가 초과하면 가장 참조 빈도가 낮은 항목을 삭제한 후 새로운 항목을 집어넣는다. 참조 횟수가 똑같은 경우 가장 오래된 항목을 삭제한다.

시간복잡도 O(1)에 항목을 삭제하기 위해 이중 연결리스트 사용.
코드 참고: https://leetcode.com/problems/lfu-cache/discuss/446443/JavaScript-Solution

LRUCache

nodes: O(1) 시간에 노드에 접근 할 수 있도록 노드들을 저장하는 객체
freqs: 이중 연결 리스트 인스턴스를 저장하는 공간, 키: 접근 빈도 횟수, 값: 키만큼의 접근 빈도 횟수가진 노드들이 모인 이중 연결 리스트

const LFUCache = function (capacity) {
  this.capacity = capacity
  this.currentSize = 0
  this.leastFreq = 0
  this.nodes = {} // 순서에 상관없이 노드들이 저장되는 공간
  this.freqs = {} // 참조횟수를 키값으로 가지는 이중 연결 리스트 저장 공간
}

Node

freq: 얼마나 자주 접근했는지 판단

class Node {
  constructor(key, value) {
    this.key = key
    this.val = value
    this.next = this.prev = null
    this.freq = 1
  }
}

DoublyLinkedList

삽입과 제거를 위해 사용된다. 삭제는 테일에서만 일어나고, 삽입은 헤드에서만 일어난다. 이유는 참조빈도가 같을 경우 생성된 지 가장 오래된 노드를 제거해야하는데, 새로 삽입하는 노드들을 헤드에만 삽입하게 되면 저절로 가장 오래된 노드는 테일쪽에 있기 때문이다.

class DoublyLinkedList {
  constructor() {
    this.head = new Node(null, null)
    this.tail = new Node(null, null)
    this.head.next = this.tail
    this.tail.prev = this.head
  }
....
}

put

  1. 신규 항목 삽입예전 항목의 교체 두 가지 경우가 있다.
  • 신규 항목 삽입
    • 캐시가 꽉 차지 않았다면 freq의 이중 연결 리스트에 삽인 된다.
    • 캐시가 꽉 찬 경우 빈도 이중 연결 리스트의 테일 항목이 삭제된 다음 신규 항목이 삽입된다.
  • 이미 존재하는 항목을 교체
    • 해당 노드의 참조빈도를 +1 한다음, 해당 참조 빈도횟수의 빈도 이중 연결 리스트 헤드로 이동시킨다.
  1. 위 과정을 거친 뒤 다음에 어떤 항목을 제거 할 지 결정한다.(leastFreq 로 결정)

get

  1. 접근 카운터를 증가시킨다.
  2. 해당 항목이 캐시에 존재 하는 경우 -1 반환
  3. 해당 항목이 캐시에 존재하는 경우 항목의 빈도 +1 한 다음, 해당 함목을 빈도 이중 리스트의 헤드로 이동시킨다.
  4. 위 과정을 거친 뒤 다음에 어떤 항목을 제거 할 지 결정한다.(leastFreq 로 결정)

동작 예시

const cache = new LFUCache(5 /* capacity */)

console.log(cache.put(1, 1)) // freqs 상태: {1: 1}
console.log(cache.put(2, 2)) // freqs 상태: {1: 2 <-> 1}
console.log(cache.put(3, 3)) // freqs 상태: {1: 3 <-> 2 <-> 1}
console.log(cache.put(4, 4)) // freqs 상태: {1: 4 <-> 3 <-> 2 <-> 1}
console.log(cache.put(5, 5)) // freqs 상태: {1:  5 <-> 4 <-> 3 <-> 2 <-> 1}
console.log(cache.get(1)) // 1 반환  freqs 상태: {1:  5 <-> 4 <-> 3 <-> 2,  2: 1}
console.log(cache.get(1)) // 1 반환  freqs 상태: {1:  5 <-> 4 <-> 3 <-> 2,  3: 1}
console.log(cache.get(1)) // 1 반환  freqs 상태: {1:  5 <-> 4 <-> 3 <-> 2,  4: 1}
console.log(cache.put(6, 6)) // freqs 상태: {1:  6 <-> 5 <-> 4 <-> 3,   4: 1}
console.log(cache.get(6)) // 1 반환  freqs 상태: {1:  5 <-> 4 <-> 3 <-> 2,  4: 1  2:6}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant