在Swift中探索算法时,如果不使用funcs shiftLeft/ ,就无法在swift中找到阵列旋转的算法shiftRight。
shiftLeft
shiftRight
C具有这种优美的算法,其时间复杂度为O(N):
/* Function to left rotate arr[] of size n by d */ void leftRotate(int arr[], int d, int n) { rvereseArray(arr, 0, d-1); rvereseArray(arr, d, n-1); rvereseArray(arr, 0, n-1); } /*Function to reverse arr[] from index start to end*/ void rvereseArray(int arr[], int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } }
我正在努力将其转换为快速:
func rotate(array:[Int], positions:Int, arSize:Int) { var a = array var p = positions var s = arSize reverseArray(array: a, start: 0, end: p-1) reverseArray(array: a, start: p, end: s-1) reverseArray(array: a, start: 0, end: s-1) } func reverseArray(array: [Int], start:Int, end:Int) { var a = array var s = start var e = end var temp = 0 while s < e { temp = a[s] a[s] = a[e] a[e] = temp s += 1 e -= 1 } }
据我了解,为了迅速,我们需要指定返回类型。如何配置它们而不增加空间(内存)复杂性?(即,不创建新的临时数组)
这个问题与其他问题不同,因为它returns与C相比如何快速工作。
returns
编辑更新:
Swift 5或更高版本
extension RangeReplaceableCollection { mutating func rotate(positions: Int) { let index = self.index(startIndex, offsetBy: positions, limitedBy: endIndex) ?? endIndex let slice = self[..<index] removeSubrange(..<index) insert(contentsOf: slice, at: endIndex) } }
extension RangeReplaceableCollection where Self: BidirectionalCollection { mutating func rotate(positions: Int, size: Int) { let index = self.index(startIndex, offsetBy: positions, limitedBy: endIndex) ?? endIndex let end = self.index(index, offsetBy: size - positions, limitedBy: self.index(before: endIndex)) ?? endIndex replaceSubrange(..<index, with: self[..<index].reversed()) replaceSubrange(index..<end, with: self[index..<end].reversed()) replaceSubrange(..<end, with: self[..<end].reversed()) } }
var test = [1,2,3,4,5,6,7,8,9,10] test.rotate(positions: 3) // [4, 5, 6, 7, 8, 9, 10, 1, 2, 3] var test2 = "1234567890" test2.rotate(positions: 3) // "4567890123"