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.
这道题因为js有pop和unshift方法而变得格外简单。。。。
var rotate = function(nums, k) {
//1
// var num = nums.length;
// k = k%num;
// for (var i = 0; i<k; i++) {
// nums.unshift(nums.pop());
// }
//2
// var num = nums.length;
// k = k%num;
// k = nums.length-k;
// for (var i = 0; i<k; i++) {
// nums.push(nums.shift());
// }
//3
// var num = nums.length;
// k = k%num;
// var deleted = nums.splice(num-k,k);
// for (var i = deleted.length-1; i>=0;i--)
// nums.unshift(deleted[i]);
};
但是对于java这样的语言来说就不是了。
我们这样做,[1,2,3,4,5,6,7] k=3
先全反过来
[7,6,5,4,3,2,1]
反前k个
[5,6,7,4,3,2,1]
反后面的
[5,6,7,1,2,3,4]
神奇吧~
var rotate = function(nums, k) {
var num = nums.length;
k = k%num;
nums.reverse();
for (var i = 0; i < parseInt(k/2); i++) {
var temp = nums[i];
nums[i] = nums[k-i-1];
nums[k-i-1] = temp;
}
for (i = k; i < parseInt((k+num)/2); i++) {
var temp = nums[i];
nums[i] = nums[k+num-i-1];
nums[k+num-i-1] = temp;
}
};