-
-
Notifications
You must be signed in to change notification settings - Fork 605
Expand file tree
/
Copy pathRotateArray.java
More file actions
30 lines (26 loc) · 734 Bytes
/
RotateArray.java
File metadata and controls
30 lines (26 loc) · 734 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
package problems.easy;
/**
* Created by sherxon on 2016-12-27.
*/
public class RotateArray {
/**
* The idea is simple. First we will reverse all array elements. Then do another reversion of elements
* up to given kth-1 index and the of part of the array. Voila! rotated :)
* Time complexity is O(N) + O(N) = O(N);
* */
public void rotate(int[] a, int k) {
k %= a.length;
reverse(a, 0, a.length - 1);
reverse(a, 0, k - 1);
reverse(a, k, a.length - 1);
}
private void reverse(int[] a, int lo, int hi) {
while (lo < hi) {
int temp = a[lo];
a[lo] = a[hi];
a[hi] = temp;
lo++;
hi--;
}
}
}