Rotate Array in Swift

前端 未结 10 869
终归单人心
终归单人心 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:04

    // a is the array to be left rotated // d is the number of unit for left rotation

    func rotLeft(a: [Int], d: Int) -> [Int] {
        var a = a
        for index in 0...(d - 1) {
           a.append(a[0])
           a.remove(at: 0)
         }
        return a
     }
    

    // calling Function

    rotLeft(a: [1,2,3,4,5], d: 4)
    

    // OutPut [5, 1, 2, 3, 4]

提交回复
热议问题