Java - 旋转数组 [英] Java - Rotating array

查看:24
本文介绍了Java - 旋转数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以目标是将数组中的元素向右旋转a次.举个例子;如果 a==2,则 array = {0,1,2,3,4} 会变成 array = {3,4,0,1,2}

So the goal is to rotate the elements in an array right a times. As an example; if a==2, then array = {0,1,2,3,4} would become array = {3,4,0,1,2}

这是我所拥有的:

for (int x = 0; x <= array.length-1; x++){
    array[x+a] = array[x];
}

然而,当 [x+a] 大于数组的长度时,这无法解释.我读到我应该将较大的存储在不同的数组中,但看到 a 是可变的,我不确定这是最好的解决方案.提前致谢.

However, this fails to account for when [x+a] is greater than the length of the array. I read that I should store the ones that are greater in a different Array but seeing as a is variable I'm not sure that's the best solution. Thanks in advance.

推荐答案

向代码中添加模数组长度:

Add a modulo array length to your code:

// create a newArray before of the same size as array

// copy
for(int x = 0; x <= array.length-1; x++){
  newArray[(x+a) % array.length ] = array[x];
}

您还应该创建一个新的 Array 来复制到其中,这样您就不会覆盖稍后需要的值.

You should also create a new Array to copy to, so you do not overwrite values, that you'll need later on.

这篇关于Java - 旋转数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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