1. 문제
https://programmers.co.kr/learn/courses/30/lessons/17680
코딩테스트 연습 - [1차] 캐시
3 [Jeju, Pangyo, Seoul, NewYork, LA, Jeju, Pangyo, Seoul, NewYork, LA] 50 3 [Jeju, Pangyo, Seoul, Jeju, Pangyo, Seoul, Jeju, Pangyo, Seoul] 21 2 [Jeju, Pangyo, Seoul, NewYork, LA, SanFrancisco, Seoul, Rome, Paris, Jeju, NewYork, Rome] 60 5 [Jeju, Pangyo, S
programmers.co.kr
2. 나의 풀이
import java.util.*;
class Solution {
public int solution(int cacheSize, String[] cities) {
if(cacheSize == 0) {
return cities.length * 5;
}
int answer = 0;
Queue q = new LinkedList();
for(int i = 0; i < cities.length; i = i + 1) {
if(q.contains(cities[i].toUpperCase())) {
q.remove(cities[i].toUpperCase());
q.add(cities[i].toUpperCase());
answer += 1;
}else {
if(q.size() == cacheSize) {
q.poll();
q.add(cities[i].toUpperCase());
answer += 5;
}else {
q.add(cities[i].toUpperCase());
answer += 5;
}
}
}
return answer;
}
}
3. 다른 사람 풀이
import java.util.LinkedHashMap;
import java.util.Map;
class Solution {
public int solution(int cacheSize, String[] cities) {
int answer = 0;
LRU<String, String> clsTemp = LRU.newInstance(cacheSize);
for (int i = 0; i < cities.length; i++) {
String sTemp = cities[i].toUpperCase();
if(clsTemp.containsKey(sTemp)) {
answer++;
}else {
answer +=5;
}
clsTemp.put(sTemp, sTemp);
}
return answer;
}
}
class LRU<K, V> extends LinkedHashMap<K, V> {
private int size;
private LRU(int size) {
super(size, 0.75f, true);
this.size = size;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
public static <K,V> LRU<K,V> newInstance(int size) {
return new LRU<K,V>(size);
}
}
'알고리즘 공부 > 프로그래머스' 카테고리의 다른 글
(Java)프로그래머스 코딩테스트 연습 - 2018 KAKAO BLIND RECRUITMENT - [3차] 압축 (0) | 2020.12.08 |
---|---|
(Java)프로그래머스 코딩테스트 연습 - 2019 KAKAO BLIND RECRUITMENT - 오픈채팅방 (0) | 2020.12.01 |
(Java)프로그래머스 코딩테스트 연습 - 2018 KAKAO BLIND RECRUITMENT - [1차] 프렌즈4블록 (0) | 2020.11.30 |
(Java)프로그래머스 코딩테스트 연습 - 2018 KAKAO BLIND RECRUITMENT - [1차] 뉴스 클러스터링 (0) | 2020.11.29 |
(Java)프로그래머스 코딩테스트 연습 - 2017팁스타운 - 예상 대진표 (0) | 2020.11.29 |