[PROG] 42578 위장 옷차림(해쉬맵)

호호빵·2022년 12월 6일
0

Algorithm

목록 보기
45/46

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42578

나의 풀이

class Solution {
    public int solution(String[][] clothes) {
        int answer = 0;

        Map<String, Integer> clothesCount = new HashMap<>();

        for (int i = 0; i < clothes.length; i++) {
            if (clothesCount.containsKey(clothes[i][1])) {
                int cur = clothesCount.get(clothes[i][1]) + 1;
                clothesCount.put(clothes[i][1], cur);
            } else {
                clothesCount.put(clothes[i][1], 1);
            }
        }

        int powOfResult = 1;
        for (String key: clothesCount.keySet()) {
            powOfResult *= clothesCount.get(key);
        }

        answer = clothes.length + powOfResult;


        return answer;
    }
}
  • 1개의 아이템으로 입을 수 있는 경우 + 2개 + 3개 + 4개 ... 로 구해야한다.

다른풀이

<경우의  구하는 >

- 상의의 수를 A, 하의의 수를 B라고 하면 상의와 하의의 조합하는 경우의 수는 A * B 
- 상의만 선택하고 하의는 선택하지 않을 수도 있고, 하의만 선택하고 상의를 선택하지 않을 수도 
  있기 때문에 (A+1)*(B+1)의 경우의 수가 나옴 
- 여기서 아무것도 입지 않는 수가 있을 수 있기 때문에 최종적으로 -1 해줌

ex) 
상의 3가지, 하의 4가지
4 * 5 - 1 = 19가지 경우의 수
  • 경우의 수 구하는 공식을 사용하고, Map에 추가해줄 때는 getOrDefault를 사용하여 리팩토링

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;

        Map<String, Integer> clothesCount = new HashMap<>();

        for (int i = 0; i < clothes.length; i++) {
            clothesCount.put(clothes[i][1], clothesCount.getOrDefault(clothes[i][1], 0) + 1);
        }

        for (String key: clothesCount.keySet()) {
            answer *= (clothesCount.get(key) + 1);
        }

        answer -= 1;

        return answer;
    }
}

더 알아보기

  • iterator을 활용한 풀이와 스트림을 활용한 풀이도 있지만 지금은 별로 와닿지도 않고 성능도 별로고 잘 사용할 수 없을 것 같다.
    스트림... 스트림...!!
import java.util.*;
import static java.util.stream.Collectors.*;

class Solution {
    public int solution(String[][] clothes) {
        return Arrays.stream(clothes)
                .collect(groupingBy(p -> p[1], mapping(p -> p[0], counting())))
                .values()
                .stream()
                .collect(reducing(1L, (x, y) -> x * (y + 1))).intValue() - 1;
    }
}

프로그래머스 - 위장(해쉬맵)

profile
하루에 한 개념씩

0개의 댓글