如何对整数循环数组执行左移?
是否存在对整数循环数组执行左移的现有方法?
具体来说,给定一个包含 4 个项目 {1,2,3,4}
且移位量为 2 的数组,我想要一种将前两个字母移到数组后面的方法,使得它看起来像这样:{3,4,1,2}
。
该算法可以将圆形数组移动一位吗?
algShiftByOne(Array)
{
temp=array[0];
i=1
while(i < Array.length - 1) // Loop from 1 up to array.length == last index
{
// If there is no exception i assume it copies value from
// initial array starting from 1 up to array.length
Array[i - 1] = Array[i];
i++;
}
Array[Array.length]=temp;
}
Is there an existing method that performs a left shift on a circular array of ints?
Specifically, given an array with 4 items {1,2,3,4}
and a shift amount of 2, I would like a method that shifts the first two letters to the back of the array, making it appear like so: {3,4,1,2}
.
Would this algorithm work to shift a circular array by one?
algShiftByOne(Array)
{
temp=array[0];
i=1
while(i < Array.length - 1) // Loop from 1 up to array.length == last index
{
// If there is no exception i assume it copies value from
// initial array starting from 1 up to array.length
Array[i - 1] = Array[i];
i++;
}
Array[Array.length]=temp;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
假设您要按
n
移位:tempNumbers
n
到的每个元素最后一个,向左移动n
tempNumbers
中的元素复制到原始数组的末尾Assuming that you want to shift by
n
:tempNumbers
n
to the last one, shift it to the left byn
tempNumbers
to the end of the original array为什么不使用循环(双向)链表?在这种情况下,您只需更改“起始指针”即可。
Why don't you use a circular (doubly) linked list? In that case you only have to change your 'start pointer'.
这是一些伪代码来完成您想要的操作。
Here is some pseudo-code to do what you want.
这会将数组向左移动一位。
This would shift the array a one to the left.
这是我的尝试...(这里是 ideone.com 演示)
Here is my go at it... (here is an ideone.com demo)
我有这个作为面试问题。旋转 m 的一个简单的就地(并且有点直观) O(2n) 解决方案是获取数组,反转它,然后反转 [0, m] 和 (m, n] 子数组。我的解决方案,虽然有点不太明显,是原地的,并且 O(n) 基本上是在一个项目上将项目向前旋转一个,最终您将遍历所有元素,如果数组是距离的倍数,这就是 GCD 的位置。下面就做一个向右旋转,向左旋转留给读者作为练习:
I had this one as an interview question. A simple in place (and somewhat intuitive) O(2n) solution for rotating m is to take the array, reverse it, then reverse the [0, m] and (m, n] subarrays. My solution, though a little less obvious, is inplace and O(n). Basically the idea is you rotate items forward one at a item, and eventually you will pass through all the elements. The catch is if the array is a multiple of the distance, which is where the GCD comes in. The following will do a rotate right, rotate left is left to the reader as an exercise: