LRU : 최근에 사용하지 않은 애를 제거 ⇒ 만약에 캐쉬가 있으면 shift가 아니라 splice로 콕 짚어서 삭제할 수 있도록
function solution(cacheSize, cities) {
let cc = [];
let time = 0;
for (let i=0; i<cities.length; i++) {
cities[i] = cities[i].toLowerCase();
let ch=false;
let idx=0;
for (let j=0; j<cc.length; j++) {
if (cc[j] == cities[i]) {
ch=true;
idx=j;
break;
}
}
if (ch==true) {
time += 1;
cc.splice(idx,1);
cc.push(cities[i]);
}
else if (ch==false) {
time += 5;
cc.push(cities[i]);
}
if (cc.length > cacheSize) {
while (cc.length > cacheSize) {
cc.shift();
}
}
}
return time;
}
console.log(
solution(3,
["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo",
"Seoul", "Jeju", "Pangyo", "Seoul"]));
function solution(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);
});
return answer;
}
console.log(
solution(3,
["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo",
"Seoul", "Jeju", "Pangyo", "Seoul"]));