旋轉數組 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