[코딜리티] 레슨 4 - PermCheck (Swift)

devapploper·2024년 8월 11일

풀이1 : Set에 1부터 N까지 숫자를 모두 넣고 하나씩 빼서 크기가 0인지 확인하는 풀이.

public func solution(_ A : inout [Int]) -> Int {
    var numberSet = Set<Int>()

    for i in 1...A.count {
        numberSet.insert(i)
    }

    for number in A {
        if numberSet.contains(number) {
            numberSet.remove(number)
        } else {
            return 0
        }
    }

    if numberSet.isEmpty {
        return 1
    } else {
        return 0
    }
}

검색을 통해 발견한 풀이: 차집합으로 간단하게 풀이1의 원리를 그대로 적용한다.

public func solution(_ A : inout [Int]) -> Int {
	Set<Int>(1...A.count).subtracting(A).isEmpty ? 1 : 0
}

출처: https://codingga-dingga.tistory.com/35?category=1065789 [코끼리와 딩가딩가:티스토리]

profile
iOS, 알고리즘, 컴퓨터공학에 관련 포스트를 정리해봅니다

0개의 댓글