Swift-数组循环移位

题目:将一个含有N个元素的数组循环右移K位,要求时间复杂度为O(N).数组abcd向右移动一位是dabc.

核心代码:

` func reverseArr(arr:inout [String],k:Int) {
if arr.count == 0 {
return
}
let count:Int = arr.count
let k:Int = k % count
reverse(arr: &arr, begin: 0, end: count - k - 1)
reverse(arr: &arr, begin: k, end: count - 1)
reverse(arr: &arr, begin: 0, end: count - 1)
}

private func reverse(arr:inout [String],begin:Int,end:Int) {
    
    var low:Int = begin
    var high:Int = end
    
    while low < high {
        swap(&arr[low], &arr[high])
        low += 1
        high -= 1
    }
}

测试数据:
var reverseData:[String] = ["a","b","c","d","1","2","3","4"]
calculator.reverseArr(arr: &reverseData, k: 4)
print("FlyElephant-数组移位的数据---(reverseData)")`

你可能感兴趣的:(Swift-数组循环移位)