프로그래머스: https://school.programmers.co.kr/learn/courses/30/lessons/42628
문제를 읽어보면 어렵지않게 풀 수 있는 문제입니다. [String]을 for문으로 탐색하면서 공백을 기준으로 해야할 명령어 I,D와 숫자로 나눈후 값을 추가하거나 최댓값, 최솟값을 제거하면 되는 문제입니다.
func solution(_ operations:[String]) -> [Int] {
var queue = [Int]()
operations.forEach { operation in
let commandAndNumber = operation.split(separator: " ")
let command = commandAndNumber[0]
guard let number = Int(commandAndNumber[1]) else {
return
}
switch command {
case "I": queue.append(number)
case "D": if number > 0 {
if let max = queue.max(), let removedIndex = queue.firstIndex(of: max) {
queue.remove(at: removedIndex)
}
} else {
if let min = queue.min(), let removedIndex = queue.firstIndex(of: min) {
queue.remove(at: removedIndex)
}
}
default: break
}
}
if queue.isEmpty {
queue = [0,0]
} else {
if let max = queue.max(), let min = queue.min() {
queue = [max, min]
}
}
return queue
}