티스토리 뷰

programmers.co.kr/learn/courses/30/lessons/42862

나의 풀이

import Foundation

func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int {

    var clothes: [Int] = []

    for _ in 0..<n {
        clothes.append(1)
    }

    for i in 0..<reserve.count {
        clothes[reserve[i]-1] += 1
    }

    for i in 0..<lost.count {
        clothes[lost[i]-1] -= 1
    }

    for i in 0..<clothes.count-1 {
        if clothes[i] == 0, clothes[i+1] == 2 {
            clothes[i] = 1
            clothes[i+1] = 1
        }
    }

    for i in 1..<clothes.count {
        if clothes[i] == 0, clothes[i-1] == 2 {
            clothes[i] = 1
            clothes[i-1] = 1
        }
    }

    return clothes.filter { $0 != 0 }.count
}

그냥 문제에 적혀있는대로 for를 5번이나 써가면서 풀었다..

 

다른 사람의 풀이

import Foundation

func solution(_ n:Int, _ lost:[Int], _ reserve:[Int]) -> Int {
    var losted = lost.filter{!reserve.contains($0)}
    var reserved = reserve.filter{!lost.contains($0)}

    var ans = n - losted.count

    for i in 0..<losted.count {
        var has: Int?

        for j in 0..<reserved.count {
            if losted[i] == reserved[j] - 1 || losted[i] == reserved[j] + 1 {
                has = j
                break
            }
        }

        if let index = has {
            reserved.remove(at: index)
            ans += 1
        }
    }

    return ans
}

 

1. filter를 사용해서 도난당한 사람, 여분 있는 사람 확인 가능

 

댓글
공지사항