https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/
CyclicRotation coding task - Learn to Code - Codility
Rotate an array to the right by a given number of steps.
app.codility.com
요약
87점 → 100점.
N == 0인 경우를 체크하지 않았다. 이런 건 기본이기도 하고, 기본 테케에서 보여주지 않으니까 잘 챙기자.
검색한 것
- 함수의 파라미터 변수에 inout:
- copy-in-copy-out. 파라미터 변수를 변경할 수 있게 된다.
- 원리는 변경이 필요할 때, 초기값을 복사해서 복사된 값을 변경한다. return할 때 복사된 값을 return한다.
- 함수를 호출할 때는 add(&a: 3, b: 4) 이런 식으로 한다.
- reverse(), reversed():
- reverse() → void / O(N)
- reversed() → ReversedCollection<Self> / O(1)
나의 풀이
// 배열의 길이가 101이므로 O(n)으로 가능하다.
// 역순으로 된 큐라고 생각하면 쉽다.
// 6 7 9 8 3 뒤집기
// 7 9 8 3 6 dequeue -> enqueue
// 9 8 3 6 7 dequeue -> enqueue
// 8 3 6 7 9 dequeue -> enqueue
// 9 7 6 3 8 뒤집기
// 최적화를 위해서는 N을 K로 나눈 나머지 만큼만 움직이면 된다.
import Foundation
import Glibc
public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
if A.isEmpty {
return []
}
let move = K % A.count
A.reverse()
for _ in 0..<move {
let front = A.removeFirst()
A.append(front)
}
A.reverse()
return A
}
더 나은 풀이
public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
if A.count == K || K == 0 || A.count == 0 { return A }
let rotation = K % A.count
let range = 0...(A.count - 1 - rotation)
let firstPick = A[range]
A.removeSubrange(range)
return A + firstPick
}
// https://muizidn.medium.com/codility-cylicrotation-swift-2008877b2a71
'Dev > PS' 카테고리의 다른 글
[Swift 알고리즘] TapeEquilibrium - Codility (0) | 2024.01.17 |
---|---|
[Swift 알고리즘] PermMissingElem - Codility (0) | 2024.01.17 |
[Swift 알고리즘] FrogJmp - Codility (0) | 2024.01.17 |
[Swift 알고리즘] OddOccurrencesInArray - Codility (0) | 2024.01.12 |
[Swift 알고리즘] Binary Gap - Codility (0) | 2024.01.12 |