티스토리 뷰
문제
https://school.programmers.co.kr/learn/courses/30/lessons/42587
풀이
- 우선 순위와 해당 우선순위의 프로세스 개수를 정렬
- 프로세스를 하나씩 접근해서 우선순위를 비교 최우선 우선순위와 같으면 프로세스를 진행 같지 않으면 제일 마지막에 삽입
- 같을 경우 프로세스 진행 개수를 +1 해주고 프로세스 배열에서 삭제
- 삭제 할때 location과 시작 offset이 같으면 해당 값을 반환하고 종료
전체코드
import Foundation
func solution(_ priorities:[Int], _ location:Int) -> Int {
// 입력된 값 정리
var numberOfpriority: [Int:Int] = [:] // 우선순위에 따른 개수
for priority in priorities {
if let num = numberOfpriority[priority] {
numberOfpriority[priority] = num+1
}else {
numberOfpriority[priority] = 1
}
}
// 결과를 구하기 위한 준비
var inputArr: [(Int,Int)] = priorities.enumerated().map{ return ($0.element,$0.offset)} // (우선순위, 시작위치)
var result: Int = 0 // 실행된 프로세스 개수
var prioritySortKey: [Int] = Array(numberOfpriority.keys).sorted(by:>) // 우선순위를 내림차순 정렬
// 결과를 구하기
while !inputArr.isEmpty { // 전체 프로세스가 끝날때 까지 반복
let check: (Int,Int) = inputArr.removeFirst()
let element: Int = check.0
let offset: Int = check.1
if element == prioritySortKey.first{
result += 1
if offset == location {
return result
}
numberOfpriority[element]! -= 1 // 해당 우선순위 개수 -1
if numberOfpriority[element] == 0 { // 우선순위의 프로세스가 0개가 되면 해당 우선순위를 삭제
numberOfpriority[element] = nil
prioritySortKey.removeFirst()
}
}else {
inputArr.append(check)
}
}
return -1
}'PS > 문제 풀이' 카테고리의 다른 글
| [프로그래머스/Swift] 17677번 - [1차] 뉴스 클러스터링 (0) | 2025.02.03 |
|---|---|
| [프로그래머스/Swift] 43165번 - 타켓 넘버 (0) | 2025.02.02 |
| [프로그래머스/Swift] 64065번 - 튜플 (0) | 2025.02.01 |
| [프로그래머스/Swift] 87946번 - 피로도 (1) | 2025.01.30 |
| [프로그래머스/Swift] 42586번 - 기능개발 (0) | 2025.01.30 |
