Algorithm/프로그래머스
[프로그래머스 스위프트] 프린터
devKen
2022. 9. 21. 16:37
아이디어
푸는데 정말 오래 걸린 문제이다. 난이도 자체는 어렵지 않고 어떻게 풀어야 할지 생각도 빨리 났다. 하지만 내가 큐라는 개념을 직접 구현해서 풀려고 했고 그걸 다 암기해야 한다는 강박관념 때문에 미루고 있었다. 이 문제는 더블 스택으로 큐를 구현해서 풀면 더 빨리 구현이 가능하지만 스위프트 언어의 특성상 array를 큐처럼 사용할 수 있다. 너무 쓸데없는 포인트에 집착할 필요도 없는 거 같다.
해답
func solution(_ priorities:[Int], _ location:Int) -> Int {
var priorities = priorities
var location = location
var result = 0
while !priorities.isEmpty {
let currentMax = priorities.max()
let qFrist = priorities.removeFirst()
if currentMax != qFrist {
priorities.append(qFrist)
} else {
result += 1
if location == 0 {
return result
}
}
if location == 0 {
location = priorities.count - 1
} else {
location -= 1
}
}
return -1
}