如何旋转左边的数组元素

时间:2018-05-05 11:16:16

标签: java arrays rotation logic

我想将这些元素向左旋转。请帮帮我...

public class RotateLeft
{ 
     public static void main(String args[]) 
     { 
         int array[] ={1,2,3};
         int myarray[]= new int[3];               
         //Here is my logic                     
         for(int i=0; i<myarray.length-1; i++)
         {                         
             myarray[i]=array[i+1];
             myarray[i+1]=array[i];
         }
         System.out.print(myarray[0]+" "+myarray[1]+ " "+ myarray[2]);  
    }
}

输出应为2 3 1

1 个答案:

答案 0 :(得分:2)

试试这个:

int[] myarray = new int[array.length];
for (int i = 0; i <= myarray.length - 1; i++) {
    if (i != myarray.length - 1) {
        myarray[i] = array[i + 1];
    } else {
        myarray[i] = array[0];
    }
}