forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RotateArray.swift
39 lines (33 loc) · 1.08 KB
/
RotateArray.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Question Link: https://leetcode.com/problems/rotate-array/
* Primary idea: reverse the whole array, then reverse parts of it seperately
*
* Note: Argument of a function in Swift is let by default, so change it to var if you need to alter the value
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class RotateArray {
func rotate(_ nums: inout [Int], _ k: Int) {
var k = k % nums.count
_reverse(&nums, 0, nums.count - 1)
_reverse(&nums, 0, k - 1)
_reverse(&nums, k, nums.count - 1)
}
private func _reverse(_ nums: inout [Int], _ startIdx: Int, _ endIdx: Int) {
// edge case
if startIdx < 0 || endIdx > nums.count || startIdx >= endIdx {
return
}
var startIdx = startIdx
var endIdx = endIdx
while startIdx < endIdx {
_swap(&nums, startIdx, endIdx)
startIdx += 1
endIdx -= 1
}
}
private func _swap<T>(_ nums: inout Array<T>, _ p: Int, _ q: Int) {
(nums[p], nums[q]) = (nums[q], nums[p])
}
}