最快的算法用于圆转变ñ大小的数组的M档位档位、数组、算法、大小

2023-09-10 23:55:43 作者:墙倒众人推

什么是最快的算法圈移阵列的M个位置? 例如,[3 4 5 2 3 1 4]换档M = 2的位置应该是[1 4 3 4 5 2 3]

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]

多谢

推荐答案

如果你想为O(n)的时间也没有额外的内存使用情况(因为指定数组),请使用乔恩Bentley的书的算法,编程珠玑第二版。它交换所有元素的两倍。没有那么快,因为使用链表,但使用较少的内存,并在概念上是简单的。

If you want O(n) time and no extra memory usage (since array was specified), use the algorithm from Jon Bentley's book, "Programming Pearls 2nd Edition". It swaps all the elements twice. Not as fast as using linked lists but uses less memory and is conceptually simple.

shiftArray( theArray, M ):
    size = len( theArray )
    assert( size > M )
    reverseArray( theArray, 0, size - 1 )
    reverseArray( theArray, 0, M - 1 )
    reverseArray( theArray, M, size - 1 )

reverseArray(anArray,在startIndex,endIndex的)逆转将从startIndex元素到endIndex的顺序,包容性。

reverseArray( anArray, startIndex, endIndex ) reverses the order of elements from startIndex to endIndex, inclusive.