점심시간에 도둑이 들어, 일부 학생이 체육복을 도난당했습니다. 다행히 여벌 체육복이 있는 학생이 이들에게 체육복을 빌려주려 합니다. 학생들의 번호는 체격 순으로 매겨져 있어, 바로 앞번호의 학생이나 바로 뒷번호의 학생에게만 체육복을 빌려줄 수 있습니다. 예를 들어, 4번 학생은 3번 학생이나 5번 학생에게만 체육복을 빌려줄 수 있습니다. 체육복이 없으면 수업을 들을 수 없기 때문에 체육복을 적절히 빌려 최대한 많은 학생이 체육수업을 들어야 합니다.
전체 학생의 수 n, 체육복을 도난당한 학생들의 번호가 담긴 배열 lost, 여벌의 체육복을 가져온 학생들의 번호가 담긴 배열 reserve가 매개변수로 주어질 때, 체육수업을 들을 수 있는 학생의 최댓값을 return 하도록 solution 함수를 작성해주세요.
제한사항
func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int {
var answer = [Bool](repeating: false, count: n)
// 체육복을 잃어버린 학생 설정
for i in lost {
answer[i - 1] = true
}
for j in reserve {
let index = (j - 1) >= 0 ? (j - 1) : 0
if lost.contains(j) {
answer[index] = false
continue
}
if index - 1 >= 0, answer[index - 1] == true {
answer[index - 1] = false
} else if index + 1 < answer.count, answer[index + 1] == true {
answer[index + 1] = false
}
}
return answer.filter { $0 == false }.count
}

lost와 reserve의 중복 제거[Bool] 대신 Set 활용 → contains, remove가 O(1)이기 때문에 더욱 효율적임func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int {
var hasLost = Set(lost)
var hasReserve = Set(reserve)
// 여벌이 있지만 잃어버린 학생은 자기 입을 수 있으므로 제외
let both = hasLost.intersection(hasReserve)
hasLost.subtract(both)
hasReserve.subtract(both)
// 체육복 빌려주기
for r in hasReserve.sorted() {
if hasLost.contains(r - 1) {
hasLost.remove(r - 1)
} else if hasLost.contains(r + 1) {
hasLost.remove(r + 1)
}
}
return n - hasLost.count
}
