Today I Learned

[프로그래머스] 해시 Level 2. 위장 (JAVA) 본문

알고리즘 & 코딩테스트

[프로그래머스] 해시 Level 2. 위장 (JAVA)

하이라이터 2021. 1. 20. 02:20
728x90

해시에 의상 종류 별 개수를 넣어야되는건 알겠는데, 의상 조합을 어떻게 계산해야될지 모르겠어서 결국 컨닝함

(한 종류의 의상 수 + 1(안입는 경우의 수)) * (한 종류의 의상 수 + 1(안입는 경우의 수)) - 1(아무것도 안 입는 경우의 수)

이거랍니다.......

 

코드

import java.util.*;
class Solution {
    public int solution(String[][] clothes) {
        Map<String, Integer> cHash = new HashMap<String, Integer>(); 
        for(String[] c : clothes){
            //c[0] : 의상이름, c[1] : 의상종류
            cHash.put(c[1], cHash.getOrDefault(c[1],0)+1);
            
        }
        int result = 1;
        for(String key : cHash.keySet()){
            result *= (cHash.get(key) + 1);
        }
        return result-1;
    }
}

결과


다른 사람의 풀이 중 stream을 사용한 신박한 풀이가 보여서 가져와봤다.

 

코드

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;
    }
}

결과

(성능은 안나오네...?)

728x90
Comments