Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Example 1:
Input: nums = [1,2,3,4,5,6,7], 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]
Example 2:
Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
1 <= nums.length <= 2 * 10^4
- It's guaranteed that
nums[i]
fits in a 32 bit-signed integer. k >= 0
旋转数组。
题意跟61题几乎一样,唯一不同的是这题的 input 是数组,所以代码上没什么参考性。这个题目的思路很巧妙,叫做三步反转法。我就拿第一个例子遍历好了。数组长度为7,要往右 rotate 三步。三步反转法的思路是
start, [1, 2, 3, 4, 5, 6, 7]
整个rotate,[7, 6, 5, 4, 3, 2, 1]
rotate前k个, [5, 6, 7, 4, 3, 2, 1]
rotate后n - k个,[5, 6, 7, 1, 2, 3, 4]
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @param {number} k 4 * @return {void} Do not return anything, modify nums in-place instead. 5 */ 6 var rotate = function(nums, k) { 7 k = k % nums.length; 8 reverse(nums, 0, nums.length - 1); 9 reverse(nums, 0, k - 1); 10 reverse(nums, k, nums.length - 1); 11 }; 12 13 var reverse = function(nums, start, end) { 14 while (start < end) { 15 let temp = nums[start]; 16 nums[start] = nums[end]; 17 nums[end] = temp; 18 start++; 19 end--; 20 } 21 };
Java实现
1 class Solution { 2 public void rotate(int[] nums, int k) { 3 k = k % nums.length; 4 reverse(nums, 0, nums.length - 1); 5 reverse(nums, 0, k - 1); 6 reverse(nums, k, nums.length - 1); 7 } 8 9 private void reverse(int[] nums, int start, int end) { 10 while (start < end) { 11 int temp = nums[start]; 12 nums[start] = nums[end]; 13 nums[end] = temp; 14 start++; 15 end--; 16 } 17 } 18 }
2020年1月24日更新
还有一种JS的思路是 pop 再 shift,利用的是 JS 对 array 的各项操作。
时间O(k)
空间O(n)
1 /** 2 * @param {number[]} nums 3 * @param {number} k 4 * @return {void} Do not return anything, modify nums in-place instead. 5 */ 6 var rotate = function(nums, k) { 7 k = k % nums.length; 8 for (var i = 1; i <= k; i++) { 9 nums.unshift(nums.pop()); 10 } 11 };
相关题目