[Programmers] μΊμ‹œ

Updated:

μΊμ‹œ

μΊμ‹œ λ₯Ό ν΄λ¦­ν•˜λ©΄ λ°”λ‘œ μ΄λ™ν•œλ‹€.

μš°μ„  μΊμ‹œμ˜ κ°œλ…κ³Ό μΊμ‹œλ₯Ό ꡐ체 ν•  λ•Œ 의 μ•Œκ³ λ¦¬μ¦˜μ„ μ•Œκ³  μžˆμ–΄μ•Ό ν•œλ‹€.

이 λ¬Έμ œμ—μ„  LRU (Least Recently Used) μ•Œκ³ λ¦¬μ¦˜μ„ μ‚¬μš©ν•˜λΌκ³  ν–ˆλ‹€.

μ €λ²ˆ 학기에 운영체제λ₯Ό λ°°μš°λ©΄μ„œ νŽ˜μ΄μ§€ ꡐ체λ₯Ό ν•  λ•Œ μ•Œκ³ λ¦¬μ¦˜μ„ λ°°μ› λŠ”λ° λ˜‘κ°™μ€ κ°œλ…μ΄μ—ˆλ‹€.


LRU λŠ” 말 κ·ΈλŒ€λ‘œ κ°€μž₯ μ˜€λž˜μ „μ— μ‚¬μš© 된 μΊμ‹œλ₯Ό λ°”κΎΈλ©΄ λœλ‹€.

deque 의 Maxlen 을 μ‚¬μš©ν•˜μ—¬ μ›ν˜• 큐 처럼 μ‚¬μš© ν•˜λ©΄ κ΅¬ν˜„ ν•  수 μžˆλ‹€.

κ·Έλ ‡κ²Œ λœλ‹€λ©΄ 무쑰건 index 0 에 μžˆλŠ” μΊμ‹œκ°€ κ°€μž₯ μ˜€λž˜μ „μ— μ‚¬μš© 된 μΊμ‹œμ΄λ‹€.

ν•˜μ§€λ§Œ λ‚˜λŠ” 졜근 μ‚¬μš© ν•œ μΊμ‹œλ₯Ό λ”°λ‘œ μ €μž₯ν•΄ κ΄€λ¦¬ν–ˆλ‹€. μΊμ‹œλ₯Ό κ³ μ • μ‹œμΌœ 놓은 λ’€ κ°€μž₯ 였래 된 μΊμ‹œμ˜ index λ₯Ό μ°Ύμ•„ λ°”κΎΌ 것 이닀.

μ΄λ ‡κ²Œ λœλ‹€λ©΄ μΊμ‹œ μ‚¬μ΄μ¦ˆκ°€ λ‹€λ₯Ό λ•Œ λ§ˆλ‹€ 졜근 μ‚¬μš© ν•œ μΊμ‹œ λͺ©λ‘μ˜ 크기도 달라지고 μ‹ κ²½ μ¨μ•Όν• κ²Œ λ§Žμ•„μ§„λ‹€.

deque λ₯Ό μ‚¬μš©ν–ˆμœΌλ©΄μ„œ deque 의 μ„±μ§ˆμ„ μ‚¬μš©ν•˜μ§€ λͺ»ν–ˆλ‹€λŠ” 것이 쑰금 아쉽닀.

from collections import deque


def solution(cacheSize, cities):
	total = 0
	cache = deque()
	cities = [val.title() for val in cities]

	if cacheSize == 0:
		return len(cities) * 5

	for idx, val in enumerate(cities):
		if len(cache) < cacheSize:
			if val in cache:
				total += 1
			else:
				cache.append(val)
				total += 5
		elif len(cache) == cacheSize:
			if val in cache:
				total += 1
			else:
				lately_used = []
				lately_idx = idx - 1
				while len(lately_used) < cacheSize - 1:
					if cities[lately_idx] not in lately_used:
						lately_used.append(cities[lately_idx])
					lately_idx -= 1

				chance_val = ''
				for j in cache:
					if j not in lately_used:
						chance_val = j

				input_idx = cache.index(chance_val)
				cache.insert(input_idx, val)
				cache.remove(chance_val)
				total += 5

	return total

이 μ½”λ“œκ°€ deque μ„±μ§ˆμ„ μ™„λ²½νžˆ μ΄μš©ν•΄ LRU λ₯Ό κ΅¬ν˜„ν–ˆλ‹€κ³  μƒκ°ν•œλ‹€.

import collections


def solution(cacheSize, cities):

	cache = collections.deque(maxlen=cacheSize)
	time = 0
	
	for cur in cities:
		val = cur.lower()
		if val in cache:
			cache.remove(val)
			cache.append(val)
			time += 1
		else:
			cache.append(val)
			time += 5
		print(cache)
	return time

Categories:

Updated:

Leave a comment