Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
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]
Example 2:
Input: [-1,-100,3,99] and 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]
Note:
- 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?
解决思路:从右往左移动。
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
let x = 0;
while (x < k) {
let c = nums.pop();
nums.unshift(c);
x++;
}
};
本文深入探讨了数组旋转问题,提供了一种通过从右往左移动元素来实现数组向右旋转k步的有效解决方案。示例展示了如何将输入数组[1,2,3,4,5,6,7]在k=3的情况下,经过三次旋转得到输出数组[5,6,7,1,2,3,4]。此外,还讨论了一个包含负数的数组[-1,-100,3,99]在k=2时的旋转过程。文章挑战读者思考更多可能的解决方案,并提出了在不使用额外空间的情况下进行原地操作的优化目标。
428

被折叠的 条评论
为什么被折叠?



