Skip to content

Instantly share code, notes, and snippets.

@tiagopereira17
Last active June 22, 2016 00:09
Show Gist options
  • Save tiagopereira17/a7873eb9065363849ce8aef535567b32 to your computer and use it in GitHub Desktop.
Save tiagopereira17/a7873eb9065363849ce8aef535567b32 to your computer and use it in GitHub Desktop.
Rotate the array A, K times. Each element of A will be shifted to the right by K indexes.
public class CyclicRotation {
public int[] rotate(int[] A, int K) {
if(A == null || A.length == 0) {
return new int[0];
}
int length = A.length;
if(K > length) {
K = K % length;
}
if(K < 1) {
return A.clone();
}
int[] rotated = new int[length];
for(int i = 0; i < K; i++) {
rotated[i] = A[length - K + i];
}
int j = 0;
for(int i = K; i < length; i++) {
rotated[i] = A[j];
j++;
}
return rotated;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment