๐Algorithm
ํ๋ก๊ทธ๋๋จธ์ค ์ฝ๋ฉํ ์คํธ ํ์ด(js) > [1์ฐจ]์บ์(lv2)
devWarrior
2023. 7. 30. 21:00
๋ฌธ์ ๐ฝ
https://school.programmers.co.kr/learn/courses/30/lessons/17680
ํ๋ก๊ทธ๋๋จธ์ค
์ฝ๋ ์ค์ฌ์ ๊ฐ๋ฐ์ ์ฑ์ฉ. ์คํ ๊ธฐ๋ฐ์ ํฌ์ง์ ๋งค์นญ. ํ๋ก๊ทธ๋๋จธ์ค์ ๊ฐ๋ฐ์ ๋ง์ถคํ ํ๋กํ์ ๋ฑ๋กํ๊ณ , ๋์ ๊ธฐ์ ๊ถํฉ์ด ์ ๋ง๋ ๊ธฐ์ ๋ค์ ๋งค์นญ ๋ฐ์ผ์ธ์.
programmers.co.kr
๋ค๋ฅธ์ฌ๋ ํ์ด ๐ฝ
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;
}
๋ดํ์ด๐ฝ
1. ์ฑ๊ณต โญ
function solution(cacheSize, cities) {
let answer = 0;
let cache = []
// ex) ["newyork", "korea" ... ]
cities.map((city)=> city.toLowerCase()).forEach((city)=>{
// ์บ์์ ์ ์ฅ ๋์ด ์๋ค๋ฉด
if(cache.includes(city)){
// ์คํ์๊ฐ
answer+=1;
// stack ์กฐ์
// ํด๋น city ๋บ๋ค
cache = cache.filter((t)=> t!==city)
// ๋งจ์์ผ๋ก city ๋์ด์ค๋ค
cache.unshift(city);
}else{
// ์คํ์๊ฐ
answer+=5;
// stack ์กฐ์
// ๋งจ์์ผ๋ก city ๋์ด์ค๋ค.
cache.unshift(city);
}
cache=cache.filter((val,index) => index<=cacheSize-1)
})
return answer;
}
๋๋์ ๐ฝ
์ฒ์์ ์บ์๊ต์ฒด ์๊ณ ๋ฆฌ์ฆ์ ๋ํ ๋ฐฐ๊ฒฝ ์ง์์ด ์์ด์ ์์ฒญ ์ ๋จน์๋ค.
LRU(Least Recently Used) ๋ํ ๊ฐ๋ ์ ์ฐพ์๋ณด๊ณ cache hit ์ cache miss์ ๋ํด ์ ์ ์์๋ค.
ํด๋น ๊ฐ๋ ์ ๋ํ ์ดํด๋ฅผ ํ๊ณ ๋๋ค ์๊ณ ๋ฆฌ์ฆ์ ์ฝ๊ฒ ์งค ์ ์์๋ค.