Brushing the question Xiaobai encountered this question:
image.png

Found one interesting, but not the best way. Because the efficiency of this method is average:
image.png

But ideas very interesting

like:
nums = [1,2,3,4,5,6,7]
k = 3
This can be done.

  1. Invert the entire array as: [7,6,5,4,3,2,1]
  2. Reverse from 0 to k-1, as: [5,6,7,4,3,2,1]
  3. Reverse from k to the end, as: [5,6,7,1,2,3,4]

code show as below

/**
 * @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 % nums.length : k;
    
    reverse(nums, 0, nums.length - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, nums.length - 1);
};

function reverse(nums, i, j) {
    while(i < j) {
        swap(nums, i, j);
        i++;
        j--;
    }
}

function swap(nums, i, j) {
    let temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

topic

The topic is here https://leetcode-cn.com/problems/rotate-array/
Interested students can go to the comments to see the most efficient implementation method.


小红星闪啊闪
914 声望1.9k 粉丝

时不我待