旋转数组 java
Let’s take an array a[3,4,5,1,0] here we can see after 1 rotation the position of the array element will be a [4,5,1,0,3], after 2 left rotations a[5,1,0,3,4] and so on hence we can see after d rotation the position of the ith element will be (i-d+n)%n.
让我们看一下数组a [3,4,5,1,0],在这里我们可以看到旋转1 圈后,数组元素的位置将是[4,5,1,0,3] ,向左旋转2 圈 a [ 5,1,0,3,4]等,因此我们可以看到,在d旋转之后,第ith个元素的位置将为(i-d + n)%n 。
Because ith element will go back in left side i.e. i-d, which is the position of element from back side so we add n in i-d to get the position from beginning and we take modulo of i-d+n because here the array is in rotation i.e. after every n-1 (that is the last index ), 0 index will come so we have taken modulo to get actual position.
因为第ith个元素将在左侧返回,即id ,这是元素从背面开始的位置,所以我们在id中添加n以获得从开始的位置,并且我们对i-d + n取模,因为这里数组在旋转即在每n-1个 (即最后一个索引)之后,将出现0个索引,因此我们已取模以获取实际位置。
In the above example, you can see after 2 rotation the position of the 0th element is (0-2+5)%5 i.e. 3, hence after 2 rotation the position of the 0th element is at 3rd index.
在上面的例子中,可以在2旋转0的位置个元素是在第三索引后2旋转第0个元素的位置是(0-2 + 5)%5即,3看到的,因此。
import java.util.*;
public class Left_rotate
{
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
//number of elements in array
int n=sc.nextInt();
//number of rotation to be performed in the array
int d=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
int ele=sc.nextInt();
a[(i-d+n)%n] = ele;
}
System.out.println("Array after left rotation");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
Output
输出量
Run 1 (Rotating 6 times)
6 6
6 7 4 6 7 8
Array after left rotation
6 7 4 6 7 8
Run 2 (Rotating 6 times)
6 2
6 7 4 6 7 8
Array after left rotation
4 6 7 8 6 7
翻译自: https://www.includehelp.com/java-programs/left-rotation-in-array.aspx
旋转数组 java