问题描述:数组
189.Rotate Arrayapp
Rotate an array of n elements to the right by k steps.prototype
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].code
解题思路:element
使用数组自带的pop()方法和unshift()方法把数组最后一个取出来加入到头部。it
使用数组的slice()方法获得后k个数,再用splice()方法删去后k个数,最后用unshift方法把获得的后k个数添加到数组前面。io
代码1:function
/** * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, modify nums in-place instead. */ var rotate = function(nums, k) { let i; k = k%nums.length; for (i = 0; i < k; i++) { nums.unshift(nums.pop()); } };
代码2:方法
/** * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, modify nums in-place instead. */ var rotate = function(nums, k) { let len = nums.length; k = k%len; let nums1 = nums.slice(len - k); nums.splice(-k, k); Array.prototype.unshift.apply(nums, nums1); };