Rotate Array in Swift

前端 未结 10 827
终归单人心
终归单人心 2021-01-05 16:45

While exploring algorithms in Swift, couldn\'t find algorithm for array rotation in swift without using funcs shiftLeft / shiftRight.

C has

10条回答
  •  没有蜡笔的小新
    2021-01-05 16:52

    This solution rotates the element of time complexity O(n)

    func rotLeft(a: [Int], d: Int) -> [Int] {
       var arr = a
       var size = arr.count - 1
       for i in 0...size  {
         let newloc = (i + (arr.count - d)) % arr.count
         arr[newloc] = a[i]
       }
       return arr
    }
    

    you shouldn't use .append(x) as in the worst case it can be O(n) and you shouldn't use .remove(at: x) as its O(n) when you can avoid using those methods As when using them you basically get n + n + n which isn't that great

提交回复
热议问题