[프로그래머스] 완주하지 못한 선수 (Java / 해쉬)
문제 설명
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.
마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.
제한사항
- 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
- completion의 길이는 participant의 길이보다 1 작습니다.
참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다. - 참가자 중에는 동명이인이 있을 수 있습니다.
입출력 예
입출력 설명
예제 #1
leo는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.
예제 #2
vinko는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.
예제 #3
mislav는 참여자 명단에는 두 명이 있지만, 완주자 명단에는 한 명밖에 없기 때문에 한명은 완주하지 못했습니다.
문제 풀이
구해야 할 것은 완주하지 못한 자를 골라내는 것이다. 즉, completion 배열에는 없고 participant 배열에는 있는 사람을 찾으면 된다.
처음 생각한 것은 다음과 같다.
1. 두 배열을 정렬한다.
2. 반복문을 이용해 두 배열의 요소를 비교한다.
3. 만약 두 배열의 요소가 같지 않다면 다음의 두 가지 경우다.
3-1. 동명이인이 존재하고, 그 중 한명이 완주자가 아니다.
3-2. participant에는 존재하고 completion에는 없다. 즉, 완주자가 아니므로 participant쪽 요소를 리턴한다.
4. 반복문을 끝까지 완수했는데도 정답이 안나온다 -> participant배열의 마지막 요소를 리턴한다.
나의 풀이
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String, Integer> map = new HashMap<>();
for(String player : participant){
map.put(player, map.getOrDefault(player,0)+1);
}
for(String player : completion){
map.put(player,map.get(player) - 1);
}
for(String key : map.keySet()){
if(map.get(key) == 1){
answer = key;
}
}
return answer;
}
}
- HashMap이란?
HashMap은 Map 인터페이스를 구현한 대표적인 Map 컬렉션입니다. Map 인터페이스를 상속하고 있기에 Map의 성질을 그대로 가지고 있습니다. Map은 키와 값으로 구성된 Entry객체를 저장하는 구조를 가지고 있는 자료구조입니다. 여기서 키와 값은 모두 객체입니다. 값은 중복 저장될 수 있지만 키는 중복 저장될 수 없습니다. 만약 기존에 저장된 키와 동일한 키로 값을 저장하면 기존의 값은 없어지고 새로운 값으로 대치됩니다. HashMap은 이름 그대로 해싱(Hashing)을 사용하기 때문에 많은 양의 데이터를 검색하는 데 있어서 뛰어난 성능을 보입니다.
- getOrDefault
찾는 키가 존재한다면 찾는 키의 값을 반환하고 없다면 기본 값을 반환하는 메서드
다른사람 풀이 - 1
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
Arrays.sort(participant);
Arrays.sort(completion);
int i;
for ( i=0; i<completion.length; i++){
if (!participant[i].equals(completion[i])){
return participant[i];
}
}
return participant[i];
}
}
다른사람 풀이 - 2
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
class Solution {
public String solution(String[] participant, String[] completion) {
Map<String, Long> participantMap = Arrays.asList(participant).stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
for(String name : completion) {
Long value = participantMap.get(name) - 1L;
if(value == 0L) {
participantMap.remove(name);
} else {
participantMap.put(name, value);
}
}
return participantMap.keySet().iterator().next();
}
}
다른사람 풀이 - 3
public class Solution {
int bucketSize;
List<Entry>[] bucket;
public String solution(String[] participant, String[] completion) {
bucketSize = (completion.length / 5)+1;
bucket = new List[bucketSize];
for (int i = 0; i < completion.length; i++) {
Entry entry = get(completion[i]);
entry.value += 1;
}
for (int i = 0; i < participant.length; i++) {
Entry entry = get(participant[i]);
if (entry != null && entry.value > 0) {
entry.value -= 1;
} else {
return entry.key;
}
}
throw new RuntimeException("error");
}
private Entry get(String s) {
int idx = hash(s);
List<Entry> list = bucket[idx];
if (list == null) {
list = new List<Entry>();
Entry entry = new Entry(s, 0);
list.add(entry);
bucket[idx] = list;
return entry;
} else {
Entry entry = list.get(s);
if (entry == null) {
entry = new Entry(s, 0);
list.add(entry);
}
return entry;
}
}
private int hash(String s) {
int num = 0;
for(int i=0; i<s.length(); i++) {
num += s.codePointAt(i) * 31 + s.codePointAt(i);
}
return num % bucketSize;
}
class Entry {
String key;
int value;
public Entry(String key, int value) {
this.key = key;
this.value = value;
}
}
class List<T extends Entry> {
Node head;
public void add(T entry) {
Node nn = new Node(entry, null);
if (head == null) {
head = nn;
} else {
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = nn;
}
}
public <T extends Entry> T get(String s) {
Node node = head;
while (node != null) {
if (node.data.key.equals(s)) {
return (T) node.data;
}
node = node.next;
}
return null;
}
class Node<T extends Entry> {
T data;
Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
}
public static void main(String[] args) {
String[] p = {"mislav", "stanko", "mislav", "ana"};
String[] c = {"stanko", "ana", "mislav"};
Solution s = new Solution();
String answer = s.solution(p, c);
System.out.println(answer);
}
}