在我的java程序中,我有一个长度为5的数组,我想将数组的内容向左移动3个位置。例如[1,2,3,4,5]将成为[4,5,1,2,3]。最好的方法是什么?感谢
答案 0 :(得分:5)
您可以使用Collections.rotate
:
Integer[] arr = {1,2,3,4,5};
Collections.rotate(Arrays.asList(arr), -3);
System.out.println(Arrays.toString(arr));
输出:
[4, 5, 1, 2, 3]
答案 1 :(得分:2)
嗯,你需要临时存储一些描述。如果你有足够的内存,你可以一次性完成:
int[] buffer = new int[placesToShift];
// Save the start of the array in the buffer
System.arraycopy(array, 0, buffer, 0, placesToShift);
// Copy the rest of the array into place
System.arraycopy(array, placesToShift, array, 0, array.length - placesToShift);
// Copy the buffer into the end
System.arraycopy(buffer, 0, array, array.length - placesToShift, buffer.length);
同样值得注意的是,你总是可以通过最多 half 将数组长度作为缓冲区,通过将“左移4”作为“向右移动”来处理”
你可以通过反复移动一次,使用常量额外空间来完成。例如:
for (int i = 0; i < placesToShift; i++) {
int firstElement = array[i];
System.arraycopy(array, 1, array, 0, array.length - 1);
array[array.length - 1] = firstElement;
}
当然时间效率低,但空间效率很高。
答案 2 :(得分:2)
int [] a = {1,2,3,4,5};
int [] b = new int[a.length];
Arrays.setAll(b, (int i) -> a[(i+3)%a.length]);
System.out.println("a="+Arrays.toString(a));
System.out.println("b="+Arrays.toString(b));
打印:
a=[1, 2, 3, 4, 5]
b=[4, 5, 1, 2, 3]
答案 3 :(得分:1)
如果你需要修改数组并且只允许使用一个额外的临时数来保存一个元素,你可以这样做:
final int first = 0;
int currIndex = first;
int temp = a[currIndex];
do {
int nextIndex = (currIndex + 3) % a.length;
a[currIndex] = (nextIndex == first) ? temp : a[nextIndex];
currIndex = nextIndex;
} while (currIndex != first);
基本上意味着temp = a[0]; a[0] = a[3]; a[3] = a[1]; a[1] = a[4]; a[4] = a[2]; a[2] = temp;
这只是因为5和3是相对素数。如果不是,则必须使用first
执行上述G次,取值为0,1,..,G-1,其中G是数组长度的GCD和移位量。 (并且上述仅适用于移位量> 0,但是可以通过向其添加a.length
来处理移位量<0。)