-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path189_RotateArray
More file actions
38 lines (29 loc) · 891 Bytes
/
189_RotateArray
File metadata and controls
38 lines (29 loc) · 891 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
34
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]
Related problem: Reverse Words in a String II
public class Solution {
public void rotate(int[] nums, int k) {
if(nums.length <= 1 || k == 0) {
return;
}
if(nums.length < k) {
k = k - nums.length;
}
reverse(nums, 0, nums.length-k-1);
reverse(nums, nums.length-k, nums.length-1);
reverse(nums, 0, nums.length-1);
}
public void reverse(int[] a, int low, int high) {
while(low<high) {
int tmp = a[low];
a[low] = a[high];
a[high] = tmp;
low++;
high--;
}
}
}
programming pearls!!!!!