반응형
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
** Python
from collections import deque
CACHE_HIT = 1
CACHE_MISS = 5
def solution(cacheSize, cities):
if cacheSize == 0:
return len(cities) * CACHE_MISS
answer = 0
q = deque()
for city in cities:
_city = city.lower()
if _city in q:
answer += CACHE_HIT
index = q.index(_city)
del q[index]
q.appendleft(_city)
else:
if len(q) == cacheSize:
q.pop()
q.appendleft(_city)
answer += CACHE_MISS
return answer
추천 1등 풀이. deque 메소드를 기본으로 알아둬야 겠다.
def solution(cacheSize, cities):
import collections
cache = collections.deque(maxlen=cacheSize)
time = 0
for i in cities:
s = i.lower()
if s in cache:
cache.remove(s)
cache.append(s)
time += 1
else:
cache.append(s)
time += 5
return time
import java.util.*;
class Solution {
static final int CACHE_HIT = 1;
static final int CACHE_MISS = 5;
public int solution(int cacheSize, String[] cities) {
if(cacheSize == 0) return 5 * cities.length;
int answer = 0;
LinkedList<String> cache = new LinkedList<>();
for(int i = 0 ; i < cities.length ; ++i){
String city = cities[i].toUpperCase();
// cache hit
if(cache.remove(city)){
cache.addFirst(city);
answer += CACHE_HIT;
// cache miss
} else {
int currentSize = cache.size();
if(currentSize == cacheSize){
cache.pollLast();
}
cache.addFirst(city);
answer += CACHE_MISS;
}
}
return answer;
}
}
반응형
'프로그래머스 > level 2' 카테고리의 다른 글
[프로그래머스] 가장 큰 수 (0) | 2022.03.10 |
---|---|
[프로그래머스] 교점에 별 만들기 (0) | 2022.03.03 |
[프로그래머스] 이진 변환 반복 (0) | 2022.03.02 |
[프로그래머스] 점프와 순간 이동 (0) | 2022.02.25 |
[프로그래머스] 타겟 넘버 (0) | 2022.02.14 |