[2018 카카오 블라인드] 캐시 (JAVA)

Jiwoo Kim·2021년 3월 11일
0
post-thumbnail

문제


풀이

2학년 때 했던 컴구 과제가 생각나는 문제였다. LRU 캐시 구현하기..

  1. processCity(): cityName을 인자로 받아서 cache에 들어있는지 체크한 후 Hit 또는 Miss 처리를 한다.
    • 이 때 인자로는 대문자 cityName을 받아서 비교할 때 오류가 안 나도록 한다.
  2. processHit(): cache에 있는 기존의 City 객체 대신 currentTime이 반영된 새로운 City 객체로 갱신한다.
  3. processMiss()
    a. cacheSize가 0인 경우 cache 갱신 없이 바로 소요시간만 리턴한다.
    b. cache가 꽉 찬 경우 LRU()에서 lestRecentlyVisitedCity를 삭제한다.
    c. 새로운 City 객체를 cache에 추가한다.

코드

import java.util.*;

class Solution {
    
    private static final int HIT = 1;
    private static final int MISS = 5;

    private int cacheSize;
    private Set<City> cache = new HashSet<>();
    private int currentTime;

    public int solution(int size, String[] cities) {
        cacheSize = size;
        processCities(cities);
        return currentTime;
    }

    private void processCities(String[] cities) {
        for (String city : cities)
            currentTime += processCity(city.toUpperCase());
    }

    private int processCity(String cityName) {
        if (cache.contains(new City(cityName)))
            return processHit(cityName);
        else
            return processMiss(cityName);
    }
    
    private int processHit(String cityName) {
        cache.remove(new City(cityName));
        cache.add(new City(cityName, currentTime));
        return HIT;
    }

    private int processMiss(String cityName) {
        if (cacheSize != 0) {   
            if (cache.size() >= cacheSize) LRU();
            cache.add(new City(cityName, currentTime));
        }
        return MISS;
    }

    private void LRU() {
        City leastRecentlyVisitedCity = cache.stream().min(Comparator.comparingInt(o -> o.lastVisitedTime)).orElse(null);
        cache.remove(leastRecentlyVisitedCity);
    }
}

class City {
    String cityName;
    int lastVisitedTime;

    public City(String cityName, int lastVisitedTime) {
        this.cityName = cityName;
        this.lastVisitedTime = lastVisitedTime;
    }

    public City(String cityName) {
        this(cityName, 0);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof City)) return false;
        City city = (City) o;
        return Objects.equals(cityName, city.cityName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(cityName);
    }
}

0개의 댓글