リント(Lv.2)


質問リンク

に答える

import Foundation

func solution(_ priorities:[Int], _ location:Int) -> Int {
    var stack: [Doc] = []
    var printQueue: [Doc] = []
    
    for (index, priority) in priorities.enumerated() {
        let doc = Doc(priority, index)
        stack.append(doc)
    }
    
    while stack.count > 0 {
        var newStack: [Doc] = []
        for (index, doc) in stack.enumerated() {
            var isTopPriority = true

            for i in index..<stack.count {
                if stack[i].priority > doc.priority {
                    isTopPriority = false
                    break
                }
            }

            if isTopPriority {
                printQueue.append(doc)
                if index != stack.count - 1 {   // 마지막 인자가 아니라면
                    newStack.insert(contentsOf: stack[(index + 1)...], at: 0)
                }
                
                break
            } else {
                newStack.append(doc)
            }
        }
        
        stack = newStack
    }
    
    //print(printQueue)
    
    // 프린터기 가동 시작
    for (index, doc) in printQueue.enumerated() {
        if doc.location == location {
            return index + 1    // 몇번째로 프린트 되는가?
        }
    }
    
    return 0
}

class Doc {
    let priority: Int
    let location: Int
    
    init(_ priority: Int, _ location: Int) {
        self.priority = priority
        self.location = location
    }
}

ポスト


スタックとキューの問題
SWIFTはキューがないので本来は単独で実施すべきであるが、問題の指紋条件のため複雑さを要求する問題ではないので、Arrayのinsert/appendを用いて実現する.
特に難しい問題はない