https://school.programmers.co.kr/learn/courses/30/lessons/17680?language=python3
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
첫 풀이
1. 큐를 만들어 LRU 알고리즘을 구현
2. 기존에 있으면 삭제하고 다시 추가
3. 왼쪽에 있을수록 사용안한 단어
4. 캐시 크기 0 주의
from collections import deque
def solution(cacheSize, cities):
answer = 0
cache=deque()
if cacheSize==0:
answer=len(cities)*5
else:
for i in cities:
i=i.lower()
if i in cache:
cache.remove(i)
cache.append(i)
answer+=1
else:
answer+=5
if len(cache)>=cacheSize:
cache.popleft()
cache.append(i)
else :
cache.append(i)
return answer
더 나은 답안
1. deque에 maxlen 기능을 사용하면 사이즈에 맞게 알아서 pop하고 append 해준다
def solution(cacheSize, cities):
answer = 0
cache = collections.deque(maxlen=cacheSize)
for i in cities:
i=i.lower()
if i in cache:
cache.remove(i)
cache.append(i)
answer+=1
else:
answer+=5
cache.append(i)
return answer
java 답안
import java.util.ArrayList;
class Solution {
public static int solution(int cacheSize, String[] cities) {
int answer = 0;
ArrayList<String> list = new ArrayList<String>();
if (cacheSize == 0)
return cities.length * 5;
for (int i = 0; i < cities.length; i++) {
cities[i] = cities[i].toUpperCase();
if (list.contains(cities[i])) {
answer++;
list.remove(cities[i]);
list.add(cities[i]);
} else {
answer += 5;
if (list.size() == cacheSize) {
list.remove(0);
list.add(cities[i]);
}
else
list.add(cities[i]);
}
}
return answer;
}
}
배운 점
1. deque에 maxlen을 사용하면 pop을 알아서해준다
2. deque import를 안해도 선언하고 사용할 수 있다
반응형
'Algorithm > 프로그래머스' 카테고리의 다른 글
[프로그래머스] SQL 문제풀이 - 조건에 맞는 사용자와 총 거래금액 조회하기 (0) | 2023.04.27 |
---|---|
[프로그래머스] 파이썬 문제풀이 - 프로세스 (0) | 2023.04.25 |
[프로그래머스] 파이썬 문제풀이 - n^2 배열 자르기 (0) | 2023.04.24 |
[프로그래머스] 파이썬 문제풀이 - 등굣길 (0) | 2023.04.20 |
[프로그래머스] SQL 문제풀이 - 조건에 부합하는 중고거래 댓글 조회하기 (1) | 2023.03.13 |
댓글