[프로그래머스] Lv2 위장

O2o2✨·2020년 12월 17일
0

알고리즘

목록 보기
24/43

링크 : 프로그래머스 - 해시 > 위장


풀이(py)

def solution(clothes):
    answer = 1
    dic = dict()
    
    for value, key in clothes:
        dic[key] = dic.get(key, 1) + 1 # 옷을 선택하지 않는 경우 포함

    for value in dic.values():
        answer *= value

    return answer - 1

풀이2(js)

function solution(clothes) {
   let answer = 1;   
   const dic = new Map();
    
    for (let clothe of clothes){
        dic.set(clothe[1], (dic.get(clothe[1]) || 1) + 1);
    }
    
    for (let [k, v] of dic){
        answer *= v;
    }
    return answer - 1;
}

reduce사용한 코드도 실행해봤는데 map이 더 빠르다.


설명

  • 옷을 dictionary에 종류별로 가짓수를 더한다. 옷을 선택하지 않는 경우도 포함되기 때문에 1로 초기화한다.
  • 종류별 가짓수를 다 곱한 후 옷을 하나도 입지 않는 경우를 1 뺀다.
profile
프론트엔드 & 퍼블리셔

0개의 댓글