
unshift가 생각나지 않아서 구현하는데 고생좀 했다

내가 짠 코드에는 두 개의 문제가 있었다
function sol00(cacheSize, cities) {
let answer = 0;
let cache = [];
if (cacheSize === 0) {
return 5 * cities.length;
}
for (let city of cities) {
city = city.toLowerCase();
const index = cache.indexOf(city);
if (index !== -1) {
answer += 1;
cache.splice(index, 1);
} else {
answer += 5;
if (cache.length >= cacheSize) {
cache.pop();
}
}
cache.unshift(city);
}
return answer;
}
function sol10(cacheSize, cities) {
const MISS = 5, HIT = 1;
if (cacheSize === 0) return MISS * cities.length;
let answer = 0,
cache = [];
cities.forEach(city => {
city = city.toUpperCase();
let idx = cache.indexOf(city);
if (idx > -1) {
cache.splice(idx, 1);
answer += HIT;
} else {
if (cache.length >= cacheSize) cache.shift();
answer += MISS;
}
cache.push(city);
});
나의 코드와 다를게 없다
function sol20(cacheSize, cities) {
const map = new Map();
const cacheHit = (city, map) => {
map.delete(city);
map.set(city, city);
return 1;
};
const cacheMiss = (city, map, size) => {
if(size === 0) return 5;
(map.size === size) && map.delete(map.keys().next().value);
map.set(city, city);
return 5;
};
const getTimeCache = (city, map, size) => (map.has(city.toLocaleLowerCase()) ? cacheHit : cacheMiss)(city.toLocaleLowerCase(), map, size);
return cities.map(city => getTimeCache(city.toLocaleLowerCase(), map, cacheSize)).reduce( (a, c) => a + c, 0);
}
return answer;
}
더 효율적인것같다
sol00 : 캐시의 길이 c 만큼 const index = cache.indexOf(city); 를 도시의 갯수 n만큼 한다
sol10 : 캐시의 길이 c 만큼 const index = cache.indexOf(city); 를 도시의 갯수 n만큼 한다
sol20 : 도시의 갯수 n만큼 $O(1) 짜리인 $map.delete(map.keys().next().value);


도시의 길이에 따라서는 시간 복잡도만큼 증가했고, 캐시의 길이에 대해서는 최악의 경우까지는 증가하지 않았다.
시간 복잡도가 낮아도 기본 실행시간이 높으면 의미가 없다.
시간 복잡도에 영향을 주는 인자가 여러개인 경우 변인 통제를 통해서 시간복잡도가 낮은것과 같은 효과를 낼 수 있다.