目录

题目

给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

示例 1:

输入: [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:

输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100]

解释:

向右旋转 1 步: [99,-1,-100,3]

向右旋转 2 步: [3,99,-1,-100]

答案

解法1:

const rotate = (nums, k) => {    for(var i = 0; i<k; i++){        nums.unshift(nums.pop());    }    return nums;}

解法2:

const rotate = (nums, k) => {    const n = nums.length;    let tmpEnd = 0;    let tmpPrev = 0;    for(let i = 0; i<k; i++) {        tmpEnd = nums[n-1];        for(let r = 0; r<n; r++) {            tmpPrev = nums[r];            nums[r] = tmpEnd;            tmpEnd = tmpPrev;        }    }    return nums};

解法3:

const rotate = (nums, k) => {    const n = nums.length;    let reversePoint = n - k%n;    reversePoint != 0 && (nums = nums.slice(reversePoint).concat(nums.slice(0, reversePoint)));    return nums;}

解法4:

const rotate = (nums, k) => {    const n = nums.length;    let newArr = new Array(n);    for(let i = 0;i<n; i++){        newArr[(i+k)%n] = nums[i];    }        for(let r = 0; r<n; r++){        nums[r] = newArr[r];    }      return nums  }

以上就是JS算法题解旋转数组方法示例的详细内容,更多关于JS算法题解旋转数组的资料请关注脚本之家其它相关文章!