数组旋转 k 位

189. Rotate Array

1
2
3
4
5
6
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
1
2
3
4
5
6
7
8
9
public void rotate(int[] nums, int k) {
if (nums.length == 1) return ;

int n = nums.length;
k = k % n; // prevent unnecessary rotate
reverse(nums, 0, n-k-1);
reverse(nums, n-k, n-1);
reverse(nums, 0, n-1);
}