📍 문제 설명
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", "Ro
programmers.co.kr
💡 접근
cache hit / miss 일 때만 잘 처리해주면 되는 문제였다.
👩💻 코드
import java.io.*;
import java.util.Arrays;
public class Solution {
public int solution(int cacheSize, String[] cities) {
int answer = 0;
if(cacheSize == 0) return cities.length * 5;
String[] cacheArr = new String[cacheSize];
for(int i = 0; i < cities.length; i++) {
cities[i] = cities[i].toLowerCase();
int pos = -1;
//hit 났을 때의 인덱스
for(int j = 0; j < cacheSize; j++) {
if (cities[i].equals(cacheArr[j])) pos = j;
}
if(pos == -1) {
answer += 5;
for(int j = cacheSize-1; j >= 1; j--) {
cacheArr[j] = cacheArr[j - 1];
}
}
else {
answer += 1;
for(int j = pos; j >= 1; j--) {
cacheArr[j] = cacheArr[j - 1];
}
}
cacheArr[0] = cities[i];
}
System.out.println(answer);
return answer;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Solution s = new Solution();
String[] cities = {"Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"};
s.solution(3, cities);
}
}
'Algorithm > programmers' 카테고리의 다른 글
[2018 카카오 블라인드 3차]압축 (0) | 2022.04.14 |
---|---|
[2018 카카오 블라인드 3차]방금그곡 (0) | 2022.04.13 |
[2018 카카오 블라인드 1차]프렌즈4블록 (0) | 2022.04.11 |
[2021 카카오 블라인드]순위 검색★ (0) | 2022.04.02 |
[2019 카카오 인턴십]튜플 (0) | 2022.04.01 |