2학년 때 했던 컴구 과제가 생각나는 문제였다. LRU 캐시 구현하기..
processCity()
: cityName
을 인자로 받아서 cache
에 들어있는지 체크한 후 Hit
또는 Miss
처리를 한다.cityName
을 받아서 비교할 때 오류가 안 나도록 한다.processHit()
: cache
에 있는 기존의 City
객체 대신 currentTime
이 반영된 새로운 City
객체로 갱신한다.processMiss()
cacheSize
가 0인 경우 cache
갱신 없이 바로 소요시간만 리턴한다.cache
가 꽉 찬 경우 LRU()
에서 lestRecentlyVisitedCity
를 삭제한다.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);
}
}