Brushing the question Xiaobai encountered this question:
Found one interesting, but not the best way. Because the efficiency of this method is average:
But ideas very interesting
like:
nums = [1,2,3,4,5,6,7]
k = 3
This can be done.
- Invert the entire array as: [7,6,5,4,3,2,1]
- Reverse from 0 to k-1, as: [5,6,7,4,3,2,1]
- Reverse from k to the end, as: [5,6,7,1,2,3,4]
code show as below
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
k = k > nums.length ? k % nums.length : k;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
};
function reverse(nums, i, j) {
while(i < j) {
swap(nums, i, j);
i++;
j--;
}
}
function swap(nums, i, j) {
let temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
topic
The topic is here https://leetcode-cn.com/problems/rotate-array/
Interested students can go to the comments to see the most efficient implementation method.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。