완주하지 못한 선수.

HASH
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.

제한사항

  • 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
  • completion의 길이는 participant의 길이보다 1 작습니다.
  • 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.
  • 참가자 중에는 동명이인이 있을 수 있습니다.

입출력 예

RESULT

1차 답안 -> Hash 알고리즘 X

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
for(int i = 0 ; i < participant.length; i++){
Boolean stop = true;
for(int j = 0 ; j < completion.length;j++){
if(participant[i].equals(completion[j])){
completion[j] = null;
stop = false;
break;
}
}
if(stop == true){
answer = participant[i];
}
}
return answer;
}
}

2차 답안 -> Hash 알고리즘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.*;

class Solution {
public String solution(String[] participant, String[] completion) {
Map<String, Integer> hash = new HashMap<>();
for (String part : participant) hash.put(part, hash.getOrDefault(part, 0) + 1);
//getOrDefault -> 중복체크를 가능하게 하기위해서 사용!
for (String comp : completion) hash.put(comp, hash.get(comp) - 1);

for (String key : hash.keySet()) {
if (hash.get(key) != 0) return key;
}

return null;
}
}

3차 답안 -> sort()메소드 이용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
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];
}
}

하루를 기록하다