티스토리 뷰

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/17680?language=java 

 

코딩테스트 연습 - [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

 

2. 풀이

문제 조건을 그대로 구현한다. ArrayList를 사용해 cache를 구현했다. 중요한 점은 2가지다.

  • 대소문자 구분하지 않으므로, toUpperCase나 toLowerCase를 써서 통일하기
  • LRU에서 hit 나왔을 때 cache 상 가장 위로 올리기

 

3. 코드

 
import java.util.*;

class Solution {
    public int solution(int cacheSize, String[] cities) {
        int answer = 0;
        ArrayList<String> cache = new ArrayList<String>();
        
        if(cacheSize == 0) return cities.length * 5;
        
        for(int i = 0; i < cities.length; i++){
            String city = cities[i].toUpperCase();
            if(cache.contains(city)){
                answer += 1;
                cache.remove(city);
            }else{
                if(cache.size() >= cacheSize){
                   cache.remove(0);
                }
                answer += 5;
            }
            cache.add(city);
        }
        
        
        return answer;
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함