题目:
leetcode189 Rotate Array
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.
思路一:复制一个和nums一样的数组,然后利用映射关系 i->(i+k)%n来交换数字
!注意深度拷贝数组
var rotate = function(nums, k) {
var temp=nums.concat();//深度拷贝
for(var i=0;i<nums.length;i++){
nums[(i+k)%nums.length]=temp[i];
}
};
思路二:
上述方法的空间复杂度为O(n),若要求空间复杂度为O(1),不能重新定义数组。
先把前n-k个数字翻转一下,再把后k个数字翻转一下,最后再把整个数组翻转一下:
1 2 3 4 5 6 7
4 3 2 1 5 6 7
4 3 2 1 7 6 5
5 6 7 1 2 3 4
var rotate = function(nums, k) {
var n=nums.length;
nums=nums.slice(0,(n-k%n)).reverse().concat(nums.slice((n-k%n)).reverse()).reverse();
};