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로 구현하였습니다.
딱히 어려울건 없었던 문제.