Algorithm/프로그래머스
[프로그래머스]해시 : 위장 (level 2) (java, c++)
HBGB
2019. 12. 17. 14:50
https://programmers.co.kr/learn/courses/30/lessons/42578
코딩테스트 연습 - 위장 | 프로그래머스
programmers.co.kr
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
class Solution {
public int solution(String[][] clothes) {
// HashMap 의상 종류, 수 입력
Map<String, Integer> hashMap = new HashMap<String, Integer>();
for (String[] cloth : clothes) {
String key = cloth[1];
if (hashMap.containsKey(key)) {
hashMap.put(key, hashMap.get(key) + 1);
continue;
}
hashMap.put(key, 1);
}
// 조합 경우의 수 계산
int answer = 1;
Iterator<Integer> it = hashMap.values().iterator();
while(it.hasNext()) {
answer *= (it.next() + 1);
}
return answer - 1;
}
}
Colored by Color Scripter
|
c++소스
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
int solution(vector<vector<string>> clothes) {
// key: 옷의 종류 , value : 개수
unordered_map<string, int> cloth_kind;
for (int i = 0; i < clothes.size(); ++i)
{
++cloth_kind[clothes[i][1]];
}
// 각각의 옷 종류 개수 + 1(안입는 경우의 수) 를 모두 곱한다음,
// 아무것도 안입는 경우 1가지를 뺀다.
int cnt = 1;
for (auto iter = cloth_kind.begin(); iter != cloth_kind.end(); ++iter)
{
cnt *= iter->second + 1;
}
return cnt - 1;
}
간단한 경우의 수 계산으로 풀 수 있는 문제였다.
TIP
조합 계산에서 처음엔 1번처럼 풀었는데,
이 문제처럼 key-value 둘 중 하나의 값만이 필요할 때에는
굳이 set를 가져오지 않고, Iterator를 활용하는 것이 더 나은 것 같다.
|
1
2
3
4
5
6
7
8
9
10
11
12
|
#1
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
answer *= (entry.getValue() + 1);
}
#2
Iterator<Integer> it = hashMap.values().iterator();
while(it.hasNext()) {
answer *= (it.next() + 1);
}
Colored by Color Scripter
|