기존의 배열 비교 알고리즘 문제와 이 문제의 가장 큰 차이점은 중복값에 대한 해결이였다.
function solution(participant, completion) {
let answer = "";
participant.sort();
completion.sort();
for (let i = 0; i < participant.length; i++) {
if (participant[i] !== completion[i]) {
answer = participant[i];
break;
}
}
return answer;
}
solution(["mislav", "stanko", "mislav", "ana"], ["stanko", "ana", "mislav"])
위와 같은 방법으로 풀 수 있는 이유는 첫번째 배열이 두번째 배열보다 길이가 크다고 정해놨기 때문이다.
만일 저 조건에서 두 배열간의 원소가 가변적이라면,
function solution(participant, completion) {
let answer = "";
participant.sort();
completion.sort();
function result(first, second) {
for (let i = 0; i < first.length; i++) {
if (first[i] !== second[i]) {
answer = first[i];
break;
}
}
}
result(participant, completion);
result(completion, participant);
return answer;
}
solution(["stanko", "ana", "mislav"], ["mislav", "stanko", "mislav", "ana"])
이와 같이 해결 할 수 있다.