Original link: leetcode-cn.com/problems/ro…

Answer:

  1. Move the array back by k bits.
  2. And the array is cyclic, meaning that when the array moves beyond its length, it fills the header.
  3. Use the new array to save the result of the move. After the move is complete, Copy the new array into the original array.
/ * * *@param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
  // Use temporary arrays to store properly sorted results
  let tempArr = [];

  // Iterate over the array, saving each element to the correct location
  for (let i = 0; i < nums.length; i++) {
    // (I + k) % nums.length is a k bit backward relative to I
    // when (I + k) % nums.length exceeds the array length, it starts at 0
    tempArr[(i + k) % nums.length] = nums[i];
  }

  // Copy the sorted result into the original array
  for (let j = 0; j < nums.length; j++) { nums[j] = tempArr[j]; }};Copy the code