Rotate Array in Swift

前端 未结 10 772
终归单人心
终归单人心 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 17:14

    You need to consider the scenario such as-

    The number of rotation can be equal/more than the size of array you need to rotate.

    To handle this scenario use modulo operator to find the actual number of rotation as you will find out rotating an array by a number equal to its size result in same array.

        func rotateLeft(array:[Int],numberOfRotation:Int) -> [Int]
        {
         let offset = numberOfRotation % array.count
         let tempResult = array[offset...] + array[..

提交回复
热议问题