Given an integer array nums[], rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
————————————————–
class RotateArray
{
static void rotateArray(int arr[],int n,int k)
{
int temp[]=new int[k];
for(int i=0;i<k;i++)//2<2
{
temp[i]=arr[n-k+i];// temp[1]=arr[4]
}
for(int i=n-1;i>=k;i–)//i=2;2>=2
{
arr[i]=arr[i-k];//arr[2]=arr[0]
}
for(int i=0;i<k;i++)//i=1;1<2
{
arr[i]=temp[i];//arr[1]=temp[1]
}
}
public static void main(String args[])
{
int arr[]={1,2,3,4,5};
int n=arr.length;//5
int k=2;//rotate by 2 position
rotateArray(arr,n,k);
System.out.println(“Rotated Array=”);
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}}