๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์บ์‹œ - Python

1. ๋ฌธ์ œ ์„ค๋ช…

์บ์‹œ ํฌ๊ธฐ์™€ ๋„์‹œ์ด๋ฆ„๋“ค์ด input์œผ๋กœ ์ฃผ์–ด์ง€๊ณ , ์ž…๋ ฅ๋œ ๋„์‹œ์ด๋ฆ„ ๋ฐฐ์—ด์„ ์ˆœ์„œ๋Œ€๋กœ ์ฒ˜๋ฆฌํ•  ๋•Œ, "์ด ์‹คํ–‰์‹œ๊ฐ„"์„ ์ถœ๋ ฅํ•œ๋‹ค.

2. LRU ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋ž€?

์บ์‹œ๋ฅผ ๋Œ€์ฒดํ•˜๋Š” ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜

์šด์˜์ฒด์ œ์—์„œ ๊ฐ€์ƒ ๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ๋ฅผ ์œ„ํ•œ ํŽ˜์ด์ง€ ๊ต์ฒด ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ค‘ ํ•˜๋‚˜

Least Recently Used Algorithm
→ ๋œป : ์ตœ๊ทผ์— ๊ฐ€์žฅ ์ ๊ฒŒ ์“ด

→ ์ตœ๊ทผ์— ๊ฐ€์žฅ ์ ๊ฒŒ ์“ด๊ฑด ๋ฒ„๋ฆฌ๊ณ , ์ƒˆ๋กœ๋‚˜์˜จ ์•„์ดํ…œ์„ ๋„ฃ๊ณ , ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ์บ์‹œ๋ฅผ ์šด์˜ํ•˜๋Š” ๊ต์ฒด ์ „๋žต ์•Œ๊ณ ๋ฆฌ์ฆ˜

3. ์ฝ”๋“œ

def solution(cacheSize, cities):
    cache = []
    time = 0

    for city in cities:
        city = city.lower() #๋„์‹œ์ด๋ฆ„์˜ ๋Œ€์†Œ๋ฌธ์ž ๊ตฌ๋ถ„ x
        if city in cache:
            time +=1
            cache.remove(city) #๊ธฐ์กด ์บ์‹œ ์ œ๊ฑฐ
            cache.append(city) #์ƒˆ๋กญ๊ฒŒ ์บ์‹œ ๋„ฃ์–ด์คŒ
        else:
            time +=5
            if cacheSize!=0:
                if len(cache) >= cacheSize: #์ƒˆ๋กœ์šด ์บ์‹œ๋ฅผ ๋„ฃ์„ ์ˆ˜ ์—†๋Š” ์ƒํ™ฉ์ด๋ผ๋ฉด
                    cache.pop(0) #๊ฐ€์žฅ ์˜ค๋ž˜๋œ ์•„์ดํ…œ ์‚ญ์ œ
                cache.append(city) #์ด๋ฒˆ์— ๋„ฃ์–ด์•ผํ•  ์•„์ดํ…œ์„ ์บ์‹œ์— ์ถ”๊ฐ€

    return time