按任意步长旋转数组,而不创建第二个数组

Mot*_*sim 4 java arrays algorithm performance

因此,对于步长为1,我想要数组:

{1, 2, 3, 4}
Run Code Online (Sandbox Code Playgroud)

成为:

{4, 1, 2, 3}
Run Code Online (Sandbox Code Playgroud)

对于大小为2的步骤,结果将是:

{3, 4, 1, 2}
Run Code Online (Sandbox Code Playgroud)

这是我现在使用的代码:

private static int[] shiftArray(int[] array, int stepSize) {
  if (stepSize == 0)
     return array;

  int shiftStep = (stepSize > array.length ? stepSize % array.length : stepSize);

  int[] array2 = new int[array.length];
  boolean safe = false;
  for (int i = 0; i < array.length; i++) {
     if (safe) {
        array2[i] = array[i - shiftStep];
     }
     else {
        array2[i] = array[array.length - shiftStep + i];
        safe = (i+1) - shiftStep >= 0;
     }
  }
  return array2;
}
Run Code Online (Sandbox Code Playgroud)

代码工作得很好,但是可以在不创建辅助数组(上面的代码中是array2)的情况下实现这一点吗?

谢谢!

Jon*_*eet 11

您可以在不创建大型数组的情况下执行此操作:

// void return type as it shifts in-place
private static void shiftArray(int[] array, int stepSize) {
    // TODO: Cope with negative step sizes etc
    int[] tmp = new int[stepSize];
    System.arraycopy(array, array.length - stepSize, tmp, 0, stepSize);
    System.arraycopy(array, 0, array, stepSize, array.Length - stepSize);
    System.arraycopy(tmp, 0, array, 0, stepSize);
}
Run Code Online (Sandbox Code Playgroud)

所以对于一个100000阵列和10的步长时,它创建一个10元件阵列,将最后一次10个元素进去,复制所述第一999990个元件要晚,然后从临时数组拷贝回起始所述阵列的.

  • 作为记录,他正在创建一个辅助数组,OPs 问题应该避免该数组。;) 无论如何,很好的解决方案。 (2认同)