[2018 카카오 1차] 캐시

Kim Jio·2022년 12월 5일
0

문제 설명

입력 형식
캐시 크기(cacheSize)와 도시이름 배열(cities)을 입력받는다.
cacheSize는 정수이며, 범위는 0 ≦ cacheSize ≦ 30 이다.
cities는 도시 이름으로 이뤄진 문자열 배열로, 최대 도시 수는 100,000개이다.
각 도시 이름은 공백, 숫자, 특수문자 등이 없는 영문자로 구성되며, 대소문자 구분을 하지 않는다. 도시 이름은 최대 20자로 이루어져 있다.
출력 형식
입력된 도시이름 배열을 순서대로 처리할 때, "총 실행시간"을 출력한다.
조건
캐시 교체 알고리즘은 LRU(Least Recently Used)를 사용한다.
cache hit일 경우 실행시간은 1이다.
cache miss일 경우 실행시간은 5이다.

LRU (Least Recently Used)

When writing data to the cache, if the cache size exceeds preset cache size, the cache data must be deleted.

The LRU algorithm is an algorithm that deletes the least used cache data.

import java.util.*;
class Solution {
    public int solution(int cacheSize, String[] cities) {
        int answer = 0;
        final int cacheHitTime = 1;
        final int cacheMissTime = 5;
        int citiesLen = cities.length;
        // if cacheSize is zero, All cache miss
        if(cacheSize == 0) {
            return cacheMissTime * citiesLen; 
        }
        
        LinkedHashMap<String, String> cache = new LinkedHashMap<>();
        for(String city : cities) {
            String lowerCity = city.toLowerCase();
            if(cache.containsKey(lowerCity)) {
                // if city name hits cache
                answer += cacheHitTime;
                // priority up
                cachePrioritySetting(cache, lowerCity);
                
                
                
            } else {
                answer += cacheMissTime;
                if(cache.size() + 1 > cacheSize) {
                    cacheLRU(cache);
                    cache.put(lowerCity, "");
                } else {
                    cache.put(lowerCity, "");
                }
            }
        }
        
        
        return answer;
    }
    
    public static void cacheLRU(LinkedHashMap<String, String> cache) {
        for(Map.Entry<String, String> ch: cache.entrySet()) {
            cache.remove(ch.getKey());
            break;
        }
    }
    public static void cachePrioritySetting(LinkedHashMap<String, String> cache, String str) {
        for(Map.Entry<String, String> ch: cache.entrySet()) {
            String s = ch.getKey();
            if(str.equals(s)) {
                cache.remove(s);
                cache.put(s, "");
                break;
            }       
           
        }
    }
   
}

I used a LinkedHashMap because I needed a data structure that had a sequence of data and looked up quickly.

And
If a cache hit occurs, the priority of the hit cache data is adjusted to the highest.

profile
what's important is an unbreakable heart

0개의 댓글