[프로그래머스] 해시: 위장 (레벨2)

김민주·2023년 2월 25일
0

알고리즘 문제풀이

목록 보기
11/14

문제

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


풀이 방법

이 문제는 경우의 수 공식을 알면 쉽게 풀 수 있는 문제이다.

예를 들어 상의의 수를 A 하의의 수를 B라고 하면 상의와 하의의 조합하는 경우의 수는 A x B이다.
이때 상의만 선택하고 하의는 선택하지 않을 수도 있고, 하의만 선택하고 상의를 선택하지 않을 수도 있다. 때문에 (A+1)x(B+1)의 경우의 수가 나온다.

여기서 아무것도 입지 않는 수가 있을 수 있기 때문에 최종적으로 -1을 해주면 (A+1)x(B+1) - 1이라는 공식을 얻을 수가 있다.


코드

import java.io.*;
import java.util.*;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
        
        HashMap<String, Integer> map = new HashMap<>();
        
        for(int i=0; i<clothes.length; i++) {
            if(map.containsKey(clothes[i][1])){
                map.put(clothes[i][1], map.get(clothes[i][1])+1);
            } else {
                map.put(clothes[i][1], 1);    
            }
        }
        
        for(Integer c : map.values()){
            answer *= c + 1;    // 각 종류의 입지 않는 경우의 수 포함하여 연산
        }
        
        return answer-1;    // 아무것도 입지 않는 경우 제외
    }
}

다른 사람 풀이

  • getOrDefault 메서드를 이용
import java.util.*;
class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
        HashMap<String, Integer> hm = new HashMap<>();
        for(int i =0; i<clothes.length; i++){
            hm.put(clothes[i][1], hm.getOrDefault(clothes[i][1],0)+1);
        }
        for(String key : hm.keySet()) {
            answer *=(hm.get(key)+1);
        }
        answer -=1;
        return answer;
    }
}
  • Iterator 인터페이스를 이용하여 연산
class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
        HashMap<String, Integer> map = new HashMap<>();
        for(int i=0; i<clothes.length; i++){
            String key = clothes[i][1];
            if(!map.containsKey(key)) {
                map.put(key, 1);
            } else {
                map.put(key, map.get(key) + 1);
            }
        }
        Iterator<Integer> it = map.values().iterator();
        while(it.hasNext()) {
            answer *= it.next().intValue()+1;
        }
        return answer-1;
    }
}
  • Stream을 이용한 풀이
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개의 댓글

관련 채용 정보