Focus On Develop ๐ŸคŸ๐ŸคŸ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ ๊ฒŒ์ž„ ๋ณธ๋ฌธ

iOS [Swift]/์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ ๊ฒŒ์ž„

๋ˆ„๋ฆฌ๋‹ฌ์ดํ‹€ 2021. 2. 16. 12:03

<๋ฌธ์ œ>


 

<์ „๋žต์งœ๊ธฐ>

ใ…‹ใ…‹ ๋ฌธ์ œ๊ฐ€ ๋”๊ธธ๋‹ค.๐Ÿ˜‚ ๋ฌธ์ œ์—์„œ ์‹œํ‚ค๋Š”๋Œ€๋กœ ํฌ๋ ˆ์ธ์˜ ์œ„์น˜๋ฅผ ์ฐพ๊ณ , ํฌ๋ ˆ์ธ์„ ์ญ‰ ๋‚ด๋ ธ์„๋•Œ ์ง‘์„ ์ธํ˜•์ด ์žˆ๋‹ค๋ฉด ๋ฐ”๊ตฌ๋‹ˆ์— ์˜ฎ๊ฒจ์„œ ์ œ์ผ ์œ„์—์žˆ๋Š” ์ธํ˜•๊ณผ ๊ฐ™์€ ์ธํ˜•์ด๋ฉด ๋‘๊ฐœ๋ฅผ ํ„ฐํŠธ๋ฆฌ๋ฉด ๋œ๋‹ค. ๊ทผ๋ฐ ๋ฌธ์ œ๋Š”.. ์ฃผ์–ด์ง€๋Š” board๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋ฉด ์ธํ˜•์„ ์ง‘์–ด์˜ฌ๋•Œ๋‚˜, ํ•ด๋‹น ๋ผ์ธ์ด ๋น„์–ด์žˆ๋Š”์ง€ ์ฒดํฌํ•˜๊ธฐ๊ฐ€ ์ข€ ์• ๋งคํ•ด์ง„๋‹ค. board[ํ–‰][์—ด]๋กœ ๋ฐ”๋กœ ์ ‘๊ทผํ•˜๊ธฐ๊ฐ€ ์ข€.. ๐Ÿ˜ญ ๊ทธ๋ž˜์„œ ๋‚˜๋Š” board๋ฅผ ์ข€ ๋” ์‰ฝ๊ฒŒ ๋ณด๊ธฐ์œ„ํ•ด ์กฐ๊ธˆ ํšŒ์ „์‹œ์ผœ์„œ ์ƒˆ๋กœ์šด dolls๋กœ ์‚ฌ์šฉํ•˜๊ธฐ๋กœ ํ–ˆ๋‹ค. ์•„๋ž˜์ฒ˜๋Ÿผ ๋Œ๋ฆฌ๋ฉด, ํ•ด๋‹น๋ผ์ธ์ด ๋น„์—ˆ๋Š”์ง€์™€ ์ œ์ผ ์œ„์—์žˆ๋Š” ์ธํ˜•์„ ๊ฐ€์ ธ์˜ค๊ธฐ ์ˆ˜์›”ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค!

์ขŒ์ธก (์ฃผ์–ด์ง€๋Š” board) / ์šฐ์ธก (ํšŒ์ „์‹œํ‚จ board)

 

<์ฝ”๋“œ>

func solution(_ board:[[Int]], _ moves:[Int]) -> Int {
    var dolls = Array(repeating: Array(repeating: 0, count: board[0].count), count: board.count)
    var basket: [Int] = []
    var result = 0
    
    for (i, x) in board.enumerated() {
        for (j, y) in x.enumerated() {
            dolls[j][i] = y
        }
    }
    
    for move in moves {
        let realX = move-1
        let notEmptyCount = dolls[realX].filter { $0 != 0 }.count
        if notEmptyCount == 0 { continue }
        let realY = dolls[realX].count - notEmptyCount
        
        let curDoll = dolls[realX][realY]
        dolls[realX][realY] = 0
        
        if basket.count > 0 && curDoll == basket[basket.count-1] {
            result += 2
            basket.popLast()
        } else {
            basket.append(curDoll)
        }
    }
    return result
}

 

<Lesson Learned>

์˜ค๋žœ๋งŒ์— ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค ใ…Žใ…Ž ์žฌ๋ฐŒ๊ตฐ ๐Ÿ‘ ๊พธ์ค€ํžˆ ํ’€์–ด์•ผ๊ฒ ๋Š”๊ฑธ!? ์ด๋ฒˆ์— ๋ฐฐ์šด๊ฒƒ์ค‘ ํ•˜๋‚˜๋Š” ๋ฐฐ์—ด์—์„œ popLost()๋ฅผ ํ•˜๋ฉด ๋งˆ์ง€๋ง‰ element๋ฅผ ์ œ๊ฑฐ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค๋Š” ์ ์ด๋‹ค. ์›๋ž˜๋Š” array.remove(at: array.count-1) ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ง€์› ์—ˆ๋Š”๋ฐ.. ๊ตณ์ด ๊ทธ๋Ÿดํ•„์š”๊ฐ€ ์—†์—ˆ๋‹ค! ใ…‹ใ…‹ ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์€ board๋ฅผ ๋Œ๋ฆฌ์ง€ ์•Š๊ณ  ํ’€๊ธด ํ–ˆ๋Š”๋ฐ.. ์•„๋ฌด๋ž˜๋„ ๊ฐœ์ธ์ ์œผ๋กœ๋Š” ์ด๋ ‡๊ฒŒ ๋Œ๋ ค์„œ ์‰ฝ๊ฒŒ ๊ตฌํ˜„ํ•˜๋Š”๊ฒŒ ์ข‹์€ ๊ฒƒ ๊ฐ™๋‹ค ๐Ÿ‘

 

 

 

 

์ถœ์ € : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ ๊ฒŒ์ž„

Comments