Issue
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]
. The goal is to rotate array A K times;
that is, each element of A will be shifted to the right by K indexes.
For example, given array A = [3, 8, 9, 7, 6]
and K = 3
, the function should return [9, 7, 6, 3, 8]
.
I want this in java. I have tried this.
public static int[] rotation(int[] a,int k) {
int[] newArray = new int[a.length];
for(int i = 0 ; i < a.length ; i++) {
int newPosition = (i + k)%a.length;
newArray[newPosition] = a[i];
}
return newArray;
}
Solution
You can also use A = B.clone();
public int[] solution(int[] A, int K) {
// write your code in Java SE 8
int [] B =new int [A.length];
for(int l=0;K>l;K--){
int j=0;
for(int i=0;i<A.length;i++){
if(i==0){
B[j]=A[A.length-1];
j++;
}
else{
B[j]=A[i-1];
j++;
}
}
//below part
/*for(int i= 0;i<A.length;i++){
A[i]=B[i];
}*/
A = B.clone();
}
return B;
}
If you like :D
Answered By - Hooney
Answer Checked By - Willingham (JavaFixing Volunteer)