Fastest algorithm for circle shift N sized array for M position

后端 未结 24 2971
温柔的废话
温柔的废话 2020-11-28 05:33

What is the fastest algorithm for circle shifting array for M positions?
For example, [3 4 5 2 3 1 4] shift M = 2 positions should be [1 4 3 4 5 2 3

24条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 05:39

    Swift 4 version for shifting array left.

    func rotLeft(a: [Int], d: Int) -> [Int] {
    
       var result = a
       func reverse(start: Int, end: Int) {
          var start = start
          var end = end
          while start < end {
             result.swapAt(start, end)
             start += 1
             end -= 1
          }
       }
    
       let lenght = a.count
       reverse(start: 0, end: lenght - 1)
       reverse(start: lenght - d, end: lenght - 1)
       reverse(start: 0, end: lenght - d - 1)
       return result
    }
    

    For example, if input array is a = [1, 2, 3, 4, 5], and left shift offset is d = 4, then result will be [5, 1, 2, 3, 4]

提交回复
热议问题