Swift Algorithm 프로그래머스 Lv1 체육복

해당 문제를 풀때 고려했던건 전채 학생의 수가 2명이상 30명이하이기 때문에 전체 탐색을 해도 시간 복잡도 상에서의 문제는 발생하지 않을 것 같아, 모든 경우를 모두 고려해보기로 하였다.


lost.contains()를 이용하여, 잃어버린 사람이 있는 경우를 우선 판단하고, 제공해줄 수 있는 사람들 리스트에서 혹시나 잃어버린 사람이 있는지를 파악하였다.

이후 제공이 가능한 사람들 중에서, 한치수 작거나, 크거나, 같거나 의 경우를 고려하여 중복으로 조건을 고려하지 않게 SkipNumber에 고려한 값을 넣어주었다.

(ex, lost : [2, 4], reserve : [3] -> 3은 2도 빌려줄 수 있고, 4도 빌려줄 수 있기 때문에)


lost와 reserve에 둘다 존재하는 경우에는 빌려주진 못하고 입을 수 있다고 판단하여 resultCount를 증가시켜 주었다.


다만, 이렇게 작성하고 나니 testcase 5,7 두가지 경우에서 틀린 상황이 발생하였는데 이 경우는 빌려줄 수 있지만 도난당해 빌려주지 못하는 경우를 skip하지 않아서 였고, 이때도 skipnumber을 추가해주는 식으로 처리하여 문제를 해결하였다.


import Foundation

func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int {
    var resultCount: Int = 0
    var skipNumber: Int = -1
    
    for i in 1..<n+1 {
        if lost.contains(i) {
            if !reserve.contains(i) {
                if reserve.contains(i - 1) && skipNumber != i - 1 {
                    if !(reserve.contains(i - 1) && lost.contains(i - 1)) {
                        resultCount += 1
                        skipNumber = i - 1    
                    }
                } else if reserve.contains(i + 1) && skipNumber != i + 1 {
                    if !(reserve.contains(i + 1) && lost.contains(i + 1)) {
                        resultCount += 1
                        skipNumber = i + 1    
                    }
                } else if reserve.contains(i) && skipNumber != i {
                    if !(reserve.contains(i) && lost.contains(i)) {
                        resultCount += 1
                        skipNumber = i
                    }
                }
            } else {
                resultCount += 1
                skipNumber = i
            }
        }  else {
            resultCount += 1
        }
        
    }
    
    return resultCount
}


해당 문제를 해결하며 참고한 반례는 다음과 같다.


최신 아티클
Swift Algorithm 프로그래머스 Lv2 타겟넘버
박익범
|
2025.04.22
Swift Algorithm 프로그래머스 Lv2 타겟넘버
[1] Swift Algorithm DFS
박익범
|
2025.04.22
[1] Swift Algorithm DFS