seungriyou / algorithm-study

์•Œ๊ณ ๋ฆฌ์ฆ˜ & SQL ๋ฌธ์ œ ํ’€์ด ๊ธฐ๋ก
https://leetcode.com/u/summer_y
0 stars 0 forks source link

[LC] 146. LRU Cache #64

Open seungriyou opened 6 months ago

seungriyou commented 6 months ago

https://leetcode.com/problems/lru-cache/

๐Ÿ˜ญ๐Ÿ˜ญ๐Ÿ˜ญ...

Approach

ref: https://www.romaglushko.com/blog/design-lru-cache/

[!caution] constraint: The functions get and put must each run in O(1) average time complexity.

  1. O(1)์— ์›์†Œ ์ฐพ๊ธฐ (for cache) โžก๏ธ hash table

    • ํ•˜์ง€๋งŒ least recently used ์›์†Œ๋ฅผ ์ฐพ์œผ๋ ค๋ฉด timestamp ๋“ฑ์„ ํ•จ๊ป˜ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š”๋ฐ, ๊ทธ ๊ณผ์ •์—์„œ O(n) complexity๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.
  2. O(1)์— least recently used ์›์†Œ ์ฐพ๊ธฐ (for LRU) โžก๏ธ linked list

    • linked list์— ์›์†Œ๋ฅผ ์ž์œ ๋กญ๊ฒŒ add & remove ํ•˜๊ธฐ ์œ„ํ•ด doubly-linked list๋กœ ๊ตฌํ˜„ํ•œ๋‹ค.
    • ์–ด๋–ค ์›์†Œ๋ฅผ ์‚ฌ์šฉ(get() or put()) ํ•  ๋•Œ๋งˆ๋‹ค ํ•ด๋‹น ์›์†Œ๋ฅผ linked list์˜ tail๋กœ ์ด๋™/์ถ”๊ฐ€ํ•˜๋ฉด, linked list์˜ head์—๋Š” least recently used ์›์†Œ๊ฐ€ ์œ„์น˜ํ•˜๊ฒŒ ๋œ๋‹ค.
    • ํ•˜์ง€๋งŒ ํ˜„์žฌ ์‚ฌ์šฉํ•˜๋ ค๋Š” ์›์†Œ๋ฅผ linked list์—์„œ ์ฐพ๋Š” ๊ณผ์ •์—์„œ O(n) complexity๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.
  3. ๋‘ ๊ฐ€์ง€์˜ ์žฅ์ ์„ ๋ชจ๋‘ ์‚ฌ์šฉํ•˜์ž! โžก๏ธ hash table + linked list

    • ์›์†Œ์˜ usage๋ฅผ doubly-linked list๋กœ ๊ด€๋ฆฌํ•˜๋˜, ํ˜„์žฌ ์‚ฌ์šฉํ•˜๋ ค๋Š” ์›์†Œ๋ฅผ linked list์—์„œ O(1)์— ์ฐพ๊ธฐ ์œ„ํ•ด hash table์„ ์•ž๋‹จ์—์„œ ์‚ฌ์šฉํ•œ๋‹ค.

      โฌ‡๏ธ ๋‹ค์Œ์˜ ๊ทธ๋ฆผ์€ linked list์˜ ๋ฐฉํ–ฅ์ด ๊ฑฐ๊พธ๋กœ์ž„ (least recently used ์›์†Œ๊ฐ€ tail์— ์œ„์น˜)

      image


[!tip] linked list๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด Node ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด๋„ ๋˜์ง€๋งŒ, ์–ด๋–ค ์›์†Œ์— ๋Œ€ํ•ด next / prev๋ฅผ ์ €์žฅํ•˜๋Š” dict ๋งŒ ๊ด€๋ฆฌํ•ด๋„ ๋œ๋‹ค!


Complexity