[프로그래머스] 1차 캐시 (파이썬, javascript)

728x90
반응형

deque은 remove나 insert함수도 있다 

1. 파이썬

def solution(cacheSize, cities):
    answer = 0
    cache=[]
    for c in cities:
        c=c.lower()
        if c not in cache:
            if cache and len(cache)>=cacheSize:
                cache.pop(0)
            if cacheSize>0:
                cache.append(c)
            answer+=5
        else:
            cache.remove(c)
            cache.append(c)
            answer+=1
    return answer

2. 자바스크립트 

function solution(cacheSize, cities) {
    const cache=[];
    var answer = 0;
    for(let i=0;i<cities.length;i+=1){
        cities[i]=cities[i].toLowerCase();
        const idx=cache.indexOf(cities[i]);
        if(idx===-1){
            answer+=5;
        }else{//캐시에 있다면 
            answer+=1;
            cache.splice(idx,1);
        }
        cache.push(cities[i]);
        if(cache.length>cacheSize)cache.shift();
    }
    
    return answer;
}
728x90
반응형
TAGS.

Comments