chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:189. 旋转数组,使用新数组Copy,JavaScript,详细注释

chencl1986 opened this issue · comments

原题链接:https://leetcode-cn.com/problems/rotate-array/

解题思路:

  1. 该题可以理解为,要求将原数组向后移动k位。
  2. 并且该数组是循环的,也就是当数组移动到超过其长度时,会填充到头部。
  3. 用新数组保存移动的结果,完成移动后,将新数组Copy到原数组中。
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
  // 使用临时数组,存放正确排序的结果
  let tempArr = [];

  // 遍历原数组,将每个元素保存到正确位置
  for (let i = 0; i < nums.length; i++) {
    // (i + k) % nums.length即为相对i向后移动了k位
    // 当(i + k) % nums.length超过数组长度时,会从0开始
    tempArr[(i + k) % nums.length] = nums[i];
  }

  // 将正确排序结果复制到原数组中
  for (let j = 0; j < nums.length; j++) {
    nums[j] = tempArr[j];
  }
};