프로그래머스 - 프린터 (Lv.2)

OQ·2022년 3월 18일
0

프로그래머스

목록 보기
20/33

문제 링크

풀이

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

profile
덕업일치 iOS 개발자

0개의 댓글