Skip to content

LeetCode题解:189. 旋转数组,JavaScript,暴力法,详细注释 #113

@chencl1986

Description

@chencl1986

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

此方法对应官方题解的第一种方法,但官方只贴了代码,没有讲解,这里梳理一下思路:

  1. 该题实际上是要求将数组的最后k位,移动到数组的前面。
  2. 假设输入: [1,2,3,4,5,6,7] 和 k = 3。
  3. 暴力法的第一层循环,每次会取出数组的最后一位。
  4. 第二层循环,当index=0时,将target放入数组的0位置,nums[0]缓存在target中,此时数组变成了[7,2,3,4,5,6]
  5. 接下来的循环就是将数组每一位向后移动的过程,第二层每次循环的结果如下:
j = 0, [7, 2, 3, 4, 5, 6, 7]
j = 1, [7, 1, 3, 4, 5, 6, 7]
j = 2, [7, 1, 2, 4, 5, 6, 7]
j = 3, [7, 1, 2, 3, 5, 6, 7]
j = 4, [7, 1, 2, 3, 4, 6, 7]
j = 5, [7, 1, 2, 3, 4, 5, 7]
j = 6, [7, 1, 2, 3, 4, 5, 6]

第二层循环完成了将数组最后一位,移动到数组第一位的过程。

  1. 之后继续第一层循环,最终将数组的后3位都移动到了数组前方,得到结果:[5,6,7,1,2,3,4]
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function (nums, k) {
  for (let i = 0; i < k; i++) {
    // 取出数组最末的一个
    let target = nums[nums.length - 1];
    // 将target移动到数组第一位,之后将数组剩余部分都往后移动一位
    for (let j = 0; j < nums.length; j++) {
      let temp = nums[j];
      nums[j] = target;
      target = temp;
    }
  }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions