- 문제 링크
https://programmers.co.kr/learn/courses/30/lessons/42587
코딩테스트 연습 - 프린터
일반적인 프린터는 인쇄 요청이 들어온 순서대로 인쇄합니다. 그렇기 때문에 중요한 문서가 나중에 인쇄될 수 있습니다. 이런 문제를 보완하기 위해 중요도가 높은 문서를 먼저 인쇄하는 프린
programmers.co.kr
난이도: Level 2
- 제출 답안
import Foundation
func solution(_ priorities:[Int], _ location:Int) -> Int {
var copyPriorities = priorities
var wait = Array(0 ... priorities.count-1)
let waitLocation = wait[location]
var indexPriorities = 0
while indexPriorities != copyPriorities.count-1 {
if copyPriorities[indexPriorities+1 ... copyPriorities.count-1].contains(where: { $0 > copyPriorities[indexPriorities] }) {
copyPriorities.append(copyPriorities.remove(at: indexPriorities))
wait.append(wait.remove(at: indexPriorities))
} else {
indexPriorities += 1
}
}
let paperSeq = wait.firstIndex { value in
value == waitLocation
}
return (paperSeq!+1)
}
- 풀이
priorities 인덱스를 체크해줄 값을 하나 초기화 해준다.(indexPriorities = 0)
그리고 대기문서 배열을 구하기 위해 priorities 크기 만큼의 배열을 하나 초기화 해준다.
var wait = Array(0 ... priorities.count-1)
priorities내부에 index 뒤부터 끝 인덱스까지의 값 중 index 값 보다 큰 값이 있다면,
priorities 의 해당 인덱스 값을 뒤로 옮겨주고 마찬가지로 대기문서(wait)의 해당 인덱스 값도 뒤로 옮겨준다.
큰 값이 없다면, 더 비교할 필요가 없기 때문에 index를 하나 증가해준다. 그렇게 마지막 요소까지 검사한다.
대기문서에서 값 정렬 전의 location 위치의 값을 구해주고 값 정렬이 끝난 뒤, 그 값의 위치를 구해준다.
처음에 Dictionary를 이용해서 풀어보려 하다가 정렬 문제로 애먹어서 배열을 두개 이용하는 방법으로 접근하니 좀 더 쉽게 풀렸다.
'iOS > 알고리즘' 카테고리의 다른 글
[프로그래머스] 크레인 인형뽑기 게임 (0) | 2021.10.04 |
---|---|
[프로그래머스] 체육복 (0) | 2021.09.21 |
[프로그래머스] 로또의 최고 순위와 최저 순위 (0) | 2021.08.26 |
[프로그래머스]기능개발 (0) | 2021.08.23 |
[프로그래머스]모의고사 (0) | 2021.08.22 |