Leetcode: Rotate Array, leetcoderotate
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]Hint:Could you do it in-place with O(1) extra space?
The idea of Naive is to save a copy of the original array and divide the original array into the first len-k elements and the last k elements, place the last k Elements in front of the first len-k elements. O (N) space is required for this operation.
In-place:
(1) reverse the array;
(2) reverse the first k elements;
(3) reverse the last n-k elements.
The first step moves the first n-k elements to the end, and moves the last k elements to the front. The next two steps put elements in the right order.
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 int len = nums.length; 4 k %= len; 5 reverse(nums, 0, len-1); 6 reverse(nums, 0, k-1); 7 reverse(nums, k, len-1); 8 } 9 10 public void reverse(int[] nums, int l, int r) {11 while (l <= r) {12 int temp = nums[l];13 nums[l] = nums[r];14 nums[r] = temp;15 l++;16 r--;17 }18 }19 }
Note that there are 4th rows, and the right shift offset k may be larger than the array length len, so k % = len;