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.
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Tags
Array
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* push(elem0, elem1, elem2, …) 向數組的末尾添加元素,並返回新的長度 * * pop() 刪除數組中最後的一個元素,同時返回該元素 * * shift() 把數組的第一個元素從其中刪除,並返回第一個元素的值 * * unshift(elem0, elem1, elem2, …) 向數組的開頭添加一個或更多元素,並返回新的長度 * * splice(start, len, elem0, elem1, elem2, …) 從數組的start位置刪除len個元素, * 同時在該位置填充elem0, elem1等元素。如果elem爲空,則直接進行刪除,同時返回被刪除的元素(array) * * slice(start, len) 從數組的start位置刪除len個元素,同時返回被刪除的元素,而原數組不變 * * concat(array) 在數組的後面接上一個數組array,同時返回拼接完成的數組,而原數組不變 * * 從上面的各個方法中,我們能夠看到,只能使用前面5個方法,最後2個方法不能修改原數組。 因此現在的思路爲:使用splice()得到最後的k個元素,然後使用unshift()把得到的數據一個個填充到數組的前面
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
// Pay attention to k, k might be larger than the lengths
k = k % nums.length;
// get the last k digits of nums
var tmp = nums.splice(-k, k);
for (var i = k - 1; i >= 0; i--) {
nums.unshift(tmp[i]);
}
};
// Reverse the array from 0 ~ k // Reverse the array from k ~ len // Reverse the array from 0 ~ len
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
var len = nums.length;
k = k%len;
reverse(nums, 0, len-k-1);
reverse(nums, len-k, len-1);
reverse(nums, 0, len-1);
};
function reverse(num, start, end) {
if(num.length<=1) {
return;
}
while(start < end) {
var temp = num[start];
num[start] = num[end];
num[end] = temp;
start++;
end--;
}
}