Java - Rotating array

后端 未结 14 1135

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

14条回答
  •  庸人自扰
    2020-11-27 19:56

    I think the fastest way would be using System.arrayCopy() which is native method:

    int[] tmp = new int[a];
    System.arraycopy(array, array.length - a, tmp, 0, a);
    System.arraycopy(array, 0, array, a, array.length - a);
    System.arraycopy(tmp, 0, array, 0, a);
    

    It also reuses existing array. It may be beneficial in some cases. And the last benefit is the temporary array size is less than original array. So you can reduce memory usage when a is small.

提交回复
热议问题