Original link: leetcode-cn.com/problems/ro…
Answer:
This method refers to the official solution and the rotation array transposition, detailed diagrams, and provides detailed notes to help understand.
/ * * *@param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
k = k % nums.length; // k can be longer than the array length,
let count = 0; // Count the number of iterations
/* * this loop implements two effects: * 1. Count is the number of moves currently made, and when count reaches the last digit of the array, the flip is over. * 2. Start is the starting position of the current flip. To handle both cases, refer to the condition */ of the while loop
for (let start = 0; count < nums.length; start++) {
let currentMoveIndex = start; // Record the starting position of the current movement
let currentMoveItem = nums[start]; // Record the start value of the current movement
do {
// Calculate the position to move to, cycle to the next k positions of the current position
let nextMoveIndex = (currentMoveIndex + k) % nums.length;
// Cache the value of the location to be moved
let temp = nums[nextMoveIndex];
// Move the current value to the next location
nums[nextMoveIndex] = currentMoveItem;
// The value of temp is the value to be moved next time
currentMoveItem = temp;
NextMoveIndex is the starting value of the next move
currentMoveIndex = nextMoveIndex;
count++; // Count moves
} while (
Nums. length and k's greatest common divisor is not 1, assuming m. * Essentially, after m while loops, start and currentMoveIndex will be equal. * Move start backward to continue the loop. Start and currentMoveIndex will not be equal if nums.length is 1. * This loop will execute until currentMoveIndex=nums.length-1, which means that the array has been traversed exactly once. * /
start !== currentMoveIndex
);
}
};
Copy the code