[프로그래머스 lev2/JS] 캐시

woolee의 기록보관소·2022년 11월 8일
0

알고리즘 문제풀이

목록 보기
85/178

문제 출처

프로그래머스 lev2 - 캐시

나의 풀이

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"]));
profile
https://medium.com/@wooleejaan

0개의 댓글