문제 | 플랫폼 | 난이도 | 유형 | 풀이 링크 | 문제 링크 |
---|---|---|---|---|---|
완주하지 못한 선수 | Programmers | Level 1 | Hash, Map | 풀이 | 문제 |
그렇다고 합니다. 오직 단 한 명의 선수를 제외한 모든 선수가 완주하였습니다.
간단히 생각해도 주어진 입력 participant과 completion를 비교해보면 participant의 크기보다 completion의 크기가 1만큼 작을 것입니다.
/**
* 정렬을 이용한 문자열 비교 풀이
*/
private static String getPersonBySort(String[] participant, String[] completion) {
// 1. Sort the array in ascending order.
Arrays.sort(participant);
Arrays.sort(completion);
// 2. Compare strings in two sorted arrays.
int len = completion.length;
for (int i = 0; i < len; i++) {
if (!participant[i].equals(completion[i])) {
return participant[i];
}
}
// 3. If at the end
return participant[len];
}
간단한 아이디어에서 출발한 풀이입니다.
두 배열에서 오직 한 문자만 다르므로,
1. 정렬을 할 시
2. 두 배열의 인덱스 순서에서 문자열이 다른 경우 participant의 에 있는 문자가 completion에 없는 것을 뜻합니다.
3. 문자열의 길이가 작은 completion의 크기를 기준으로 비교하므로 다른 경우를 발견하지 못했다면, 비교하지 못한 participant의 마지막 인덱스가 완주하지 못한 선수입니다. (무조건 완주하지 못한 선수가 한 명 있으므로)
/**
* HashMap을 이용한 풀이
*/
private static String getPersionByHashMap(String[] participant, String[] completion) {
HashMap<String, Integer> hashMap = new HashMap<>();
// 1. Put the participant array to the hashmap while increasing the value.
for (String person : participant) {
hashMap.put(person, hashMap.getOrDefault(person, 0) + 1);
}
// 2. Put the participant array into the hashmap while reducing the value.
for (String person : completion) {
hashMap.put(person, hashMap.get(person) - 1);
}
// 3. Find a key whose value is not 0.
String ans = "";
for (Entry<String, Integer> entry : hashMap.entrySet()) {
if (entry.getValue() > 0) {
ans = entry.getKey();
break;
}
}
return ans;
}