189. Rotate Array
Rotate an array of n elements to the right byk steps.
For example, with n = 7 and k = 3, the array
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]Hint:
Could you do it in-place with O(1) extra space?
given an array of n lengths, rotate it to the right by k positions.first convert k into the number in [0, n-1]. Flip the entire array, flip the number at the [0, K-1] position, and flip the rest.
note that k is positive
Rotate an array of n elements to the right byk 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]Hint:
Could you do it in-place with O(1) extra space?
given an array of n lengths, rotate it to the right by k positions.first convert k into the number in [0, n-1]. Flip the entire array, flip the number at the [0, K-1] position, and flip the rest.
note that k is positive
public void rotate(int[] nums, int k) {
int len = nums.length;
// Ensure that k is positive
k = (len + (k % len)) % len;
// Flip the entire array.
rotateCore(nums, 0, len - 1);
// Flip the array of subscript 0~k-1.
rotateCore(nums, 0, k - 1);
// Flip the array of subscript k~len-1.
rotateCore(nums, k, len - 1);
}
/**
* @param nums
* Flip the array (the subscript is closed front to back).
* @param start
* Subscript to the beginning of the flipped array
* @param end
* End subscript for flipping arrays
*/
private void rotateCore(int[] nums, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
}