最快的算法用于圆转变ñ大小的数组的M档位 [英] Fastest algorithm for circle shift N sized array for M position

查看:180
本文介绍了最快的算法用于圆转变ñ大小的数组的M档位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最快的算法圈移阵列的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.

这篇关于最快的算法用于圆转变ñ大小的数组的M档位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆