问题描述
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].
注意:k的值可能会大于n
思路1:先将整个数组逆序,然后分别对被分割开的两个部分做一次逆序
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
//
function f(arr,n){
arr.reverse();
if(n!=1){
var le = Math.ceil(n/2);
for( var i = 0; i < le; i++){
var temp = arr[i];
arr[i] = arr[k-1-i];
arr[k-1-i] = temp;
}
}
var le = Math.floor((arr.length - n)/2)+n;
var j=0;
for( var i = n; i < le; i++){
j++;
var temp = arr[i];
arr[i] = arr[arr.length - j];
arr[arr.length - j] = temp;
}
}
if(k!==0 ){
if(k<nums.length){
f(nums,k);
}
else{
k = k%nums.length;
if(k!=0){
f(nums,k);
}
}
}
};
思路2:先在k的位置对数组进行切片,然后用数组拼接
var rotate = function(nums, k) {
var le = nums.length;
if(k!==0){
if(k<le){
var arr = nums.splice(0,le-k)
for(var i=0; i<le-k; i++){
nums.push(arr[i]);
}
}
else{
k = k % nums.length;
if(k!==0){
var arr = nums.splice(0,nums.length-k);
for(var i=0; i<le-k; i++){
nums.push(arr[i]);
}
}
}
}
};