Last active
June 22, 2016 00:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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