Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 코딩테스트합격자되기
- redux
- Python
- C++
- useDispatch
- react
- json-server
- redux-saga
- 리액트
- maeil-mail
- redux-toolkit
- Get
- Algorithm
- sw expert academy
- 이코테
- programmers
- createSlice
- 항해99
- 자바
- 테코테코
- 프로그래머스
- react-redux
- SW
- java
- axios
- JavaScript
- 알고리즘
- 매일메일
- react-router
- 항해플러스
Archives
- Today
- Total
Binary Journey
[프로그래머스] 캐시 본문
반응형
출처: 프로그래머스 코딩 테스트 연습, 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 |