-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateArray.java
More file actions
33 lines (27 loc) · 888 Bytes
/
Copy pathRotateArray.java
File metadata and controls
33 lines (27 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* Design an algorithm to rotate an array/string to the right by k positions
* http://blog.csdn.net/v_july_v/article/details/6322882
*/
public class RotateArray {
public static void main(String[] args) {
char[] arr = {'a', 'b', 'c', 'd', '1', '2', '3', '4'};
int k = 3;
System.out.println("Before: " + new String(arr));
rotate(arr, k);
System.out.println("After: " + new String(arr));
}
public static void rotate(char[] arr, int k) {
k %= arr.length;
reverse(arr, 0, arr.length-1);
reverse(arr, 0, k-1);
reverse(arr, k, arr.length-1);
}
public static void reverse(char[] arr, int left, int right) {
while(left < right) {
char tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
}
}