相关疑难解决方法(0)

用于M位置的圆移N大小数组的最快算法

M位置的圆移位阵列的最快算法是什么?
例如,[3 4 5 2 3 1 4]班次M = 2个位置应该是[1 4 3 4 5 2 3].

非常感谢.

arrays puzzle algorithm math programming-pearls

32
推荐指数
4
解决办法
3万
查看次数

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

因此,对于步长为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 …
Run Code Online (Sandbox Code Playgroud)

java arrays algorithm performance

4
推荐指数
1
解决办法
986
查看次数