프로그래머스 LEVEL 2(캐시)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2022-09-22

  • 해결 방법 :
    • cities 속 city 소문자로 변경
    • cities 돌며 cache에 포함되어 있지 않다면 cache 사이즈에 맞춰 shift() 후 push(), 이 때 실횅 시간 5 증가
    • cache에 포함되어 있다면 포함된 city cache의 맨 뒤로 옮긴 후 실행 시간 1 증가
  • 회고 :
    • x
  • 코드

    function solution(cacheSize, cities) {
        let answer = 0;
        let cache = [];
        if (!cacheSize) return cities.length * 5;
        cities = cities.map((city) => city.toLowerCase());
        for (const city of cities) {
            if (!cache.includes(city)) {
                if (cache.length === cacheSize) cache.shift();
                answer += 5;
                cache.push(city);
            } else {
                answer += 1;
                cache = cache.filter((e) => e !== city);
                cache.push(city);
            }
        }
        return answer;
    }
    
  • 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges