주어진 배열은 맨 앞의 요소를 맨 뒤로 가져가는 방식으로 계속 돈다.
이 상태에서 최대값을 만나면 제외하고 다시 최대값을 만나면 제외하는 방식으로 진행되며,
최초에 자신의 위치를 알려준 요소가 제거될 경우 몇번째로 제거되었는지 알아보는 문제다.
필요한 작업 :
자신의 값을 알아내야 한다.
생각해 낸 아이디어 :
1. 배열에서 자신이 가장 큰 값일 경우는
자신의 위치 앞에 있는 자신과 같은 값의 갯수를 보고서도 결과 값을 알 수 있다. (시간 절약)
2. Array와 ArraySlice는 다르다.
ArraySlice는 서로 더하기 정도는 가능하고, Array로 형변환 하면 Array로 만들 수 있다.
import Foundation
func solution(_ priorities:[Int], _ location:Int) -> Int {
var priorities = priorities
var location = location
let myPriority = priorities[location] // 나의 위치에 있는 값
var result = 0 // 순서. 결과값.
// 내가 최대값이 될 때까지
while !priorities.isEmpty && priorities.max() != myPriority {
if let maxValue = priorities.max() {
// 맨 앞에 있다면 빠르게 작업할 수 있도록 다음의 코드를 작성한다.
if priorities.first == maxValue {
location = location == 0 ? priorities.endIndex-1 : location - 1
priorities.removeFirst()
} else {
let maxValueIndex = priorities.firstIndex(of: maxValue)!
// 나의 위치는 최대값이 발견되는 최초 인덱스의 위치만큼 이동한다.
// -1을 하는 이유는 순서 하나 당 하나의 요소가 삭제되기 때문이다.
location = location - maxValueIndex - 1
if location < 0 {
location += priorities.endIndex
}
priorities = Array(priorities[maxValueIndex+1 ..< priorities.endIndex] + priorities[0..<maxValueIndex])
}
result += 1
}
}
while priorities.firstIndex(of: myPriority) != location {
// 배열의 요소는 1~9라는 점을 이용하여 자신의 앞에 있는 최대값들을 0으로 만들어버린다.
priorities[priorities.firstIndex(of: myPriority)!] = 0
result += 1
}
//내 것이 출력되는 순서도 더해야 하므로 +1
return result+1
}