on
[해시] 위장
[해시] 위장
해시-위장
java
import java.util.*; class Solution { public int solution(String[][] clothes) { HashMap map = new HashMap<>(); for (String[] cloth : clothes) { // map.compute(cloth[1], (k, v) -> v == null ? 1 : v + 1); // compute를 이용해도 되지만, 아래 코드에 비해서 시간이 조금 더 걸린다. // compute는 언제 사용하는 건지 잘 모르겠다. 구현 코드를 보면 꽤 복잡해보인다. // (복잡해서 제대로 보진 않았다.) map.put(cloth[1], map.getOrDefault(cloth[1], 0) + 1); } Integer answer = map.values().stream().reduce(1, (a, b) -> a * (b+1)); return answer-1; } }
경우의 수 구하는 부분에서 꽤 헤맸다.
진짜 간단한 계산이었는데...ㅎㅎ(ㅂㄷㅂㄷ)
마음에 드는 다른 분들 코드도 같이 기록한다.
1.
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], summingInt(e -> 1)))) .values() .reduce(1, (x, y) -> x * (y + 1) ) - 1; } }
stream 쓸 때는 주의하라는 글을 봤었는데... 속도가 좀 떨어진다. 이 부분은 다시 한 번 확인해봐야 할 것 같다.
2.
class Solution { int typeIndex = 0; String[] types; int[] counts; public int solution(String[][] clothes) { int answer = 1; int len = clothes.length; this.types = new String[len]; this.counts = new int[len]; for(int i = 0; i < len; i++){ setKeyVal(clothes[i][1]); } for(int i = 0; i < typeIndex; i++){ answer *= (counts[i]+2); // 배열 초기화 값이 0이었으므로, 2를 더한다. } return answer - 1; } public void setKeyVal(String type){ for (int i = 0; i < types.length; i++) { if(type.equals(types[i])){ counts[i]++; return; } } types[typeIndex] = type; typeIndex++; return; } }
from http://ichmww2.tistory.com/55 by ccl(A) rewrite - 2021-09-24 01:00:44