코딩테스트
[프로그래머스] 위장
gajy
2022. 4. 1. 18:15
728x90
https://programmers.co.kr/learn/courses/30/lessons/42578
[ 나의 풀이 ]
공식을 찾아내는것이 포인트이다.
공식: (A+1)*(B+1) -1
import java.util.HashMap;
import java.util.Map;
class Solution {
public int solution(String[][] clothes) {
int answer = 1;
Map<String, Integer> clothesMap = new HashMap<>();
for(int i = 0; i < clothes.length; i++) {
clothesMap.put(clothes[i][1], clothesMap.getOrDefault(clothes[i][1],0) + 1);
}
for(String cloth : clothesMap.keySet()) {
answer *= (clothesMap.get(cloth) + 1);
}
return answer-1;
}
}
[ Iterator 사용 풀이 ]
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
class Solution {
public int solution(String[][] clothes) {
int answer = 1;
Map<String, Integer> clothesMap = new HashMap<>();
for(int i = 0; i < clothes.length; i++) {
clothesMap.put(clothes[i][1], clothesMap.getOrDefault(clothes[i][1],0) + 1);
}
Iterator<Integer> it = clothesMap.values().iterator();
while(it.hasNext()) {
answer *= (it.next().intValue() + 1);
}
return answer-1;
}
}
[ 람다 사용 풀이 ]
import java.util.Arrays;
import java.util.stream.Collectors;
class Solution {
public int solution(String[][] clothes) {
return Arrays.stream(clothes)
.collect(Collectors.groupingBy(c -> c[1], Collectors.counting()))
.values()
.stream()
.reduce(1L, (x, y) -> x * (y + 1)).intValue() -1;
}
}
728x90