๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ Programmers(Lv.3)

by seolhee2750 2021. 12. 21.
๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/42628

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ

 

programmers.co.kr

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ operations:[String]) -> [Int] {
    var queue = [Int]()
    
    for i in operations {
        let command = i.split(separator: " ").map({String($0)})
        
        if command[0] == "I" { queue.append(Int(command[1])!) }
        else if command[0] == "D" && !queue.isEmpty {
            if command[1].contains("-") { queue.sort(by: >); queue.removeLast() }
            else { queue.sort(); queue.removeLast() }
        }
    }
    
    return queue.isEmpty ? [0, 0] : [queue.max()!, queue.min()!]
}

๐Ÿ‘‰Heap ๋ฌธ์ œ!

  • queue ๋ผ๋Š” ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•˜๊ณ  ๊ฐ ๋ช…๋ น์— ๋งž๊ฒŒ ๋ฐฐ์—ด์„ ์ˆ˜์ •ํ–ˆ์Œ.
  • I ๋ช…๋ น์–ด์˜ ๊ฒฝ์šฐ์—๋Š” ๋ฐ”๋กœ queue ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰์— ๊ฐ’์„ ์‚ฝ์ž…ํ•˜์˜€์Œ.
  • D ๋ช…๋ น์–ด์˜ ๊ฒฝ์šฐ์—๋Š” queue ๋ฐฐ์—ด์ด ๋น„์–ด์žˆ์ง€๋Š” ์•Š์€์ง€ ํ™•์ธ ํ›„ ๋ช…๋ น์„ ์‹คํ–‰ํ•˜๊ฒŒ ํ•จ.
    ์ˆซ์ž์— "-"๊ฐ€ ๋ถ™์–ด์žˆ๋Š” ๊ฒฝ์šฐ ์ตœ์†Ÿ๊ฐ’์„ ์‚ญ์ œํ•ด์•ผํ•˜๋ฏ€๋กœ queue ๋ฐฐ์—ด์„ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ ํ›„ removeLast ํ–ˆ์Œ.
    ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” ์ตœ๋Œ“๊ฐ’์„ ์‚ญ์ œํ•ด์•ผํ•˜๋ฏ€๋กœ queue ๋ฐฐ์—ด์„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ ํ›„ removeLasrt ํ–ˆ์Œ.
    (removeFirst๋ฅผ ํ•˜๋Š” ๊ฒƒ์„ ํ”ผํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ์œ„์™€ ๊ฐ™์ด ์ •๋ ฌํ•˜์˜€์Œ.)

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๋ ˆ๋ฒจ 3 ์น˜๊ณ ๋Š” ๊ต‰์žฅํžˆ ์‰ฌ์šด ๋ฌธ์ œ์˜€๊ณ , removeFirst๋งŒ ํ”ผํ•ด์ฃผ๋ฉด ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€์ด ๊ฐ€๋Šฅํ–ˆ์Œ.

๋Œ“๊ธ€