题目描述
给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
示例 1:
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]
提示
解法1 扩展数组+pop
var rotate = function(nums, k) {let n=nums.length;k=k%n;for(let i=n-1;i>=0;i--){nums[i+k]=nums[i];}for(i=k-1;i>=0;i--){nums[i]=nums[n+i];nums.pop()}
};
执行结果:
解法2 借助辅助数组
var rotate = function(nums, k) {const n = nums.length;const newArr = new Array(n);for (let i = 0; i < n; ++i) {newArr[(i + k) % n] = nums[i];}for (let i = 0; i < n; ++i) {nums[i] = newArr[i];}
};
执行结果:
解法3 unshift+pop
var rotate = function(nums, k) {for(let i=0;i<k;i++){nums.unshift(nums.pop())}return nums;};
执行结果:
解法4 数组反转
const reverse = (nums, start, end) => {while (start < end) {const temp = nums[start];nums[start] = nums[end];nums[end] = temp;start += 1;end -= 1;}
}var rotate = function(nums, k) {k %= nums.length;reverse(nums, 0, nums.length - 1);reverse(nums, 0, k - 1);reverse(nums, k, nums.length - 1);
};
执行结果: