[Data structure] Leetcode rotation array

Table of contents

          1. Topic Description

          2. Topic analysis


1. Topic Description

Topic link: leetcode rotation array

Given an array, rotate the elements in the array k positions to the right, where k is a non-negative number.

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3

Output: [5,6,7,1,2,3,4]

explain:

Turn right 1 step: [7,1,2,3,4,5,6]

Turn right 2 steps: [6,7,1,2,3,4,5]

Turn right 3 steps: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2

Output: [3,99,-1,-100]

explain:

Turn right 1 step: [99,-1,-100,3]

Rotate right 2 steps: [3,99,-1,-100]

2. Topic analysis 

method 1:

First create a temporary array tmp[] 

The first step: first copy the last k numbers to the front;

The second step: copy the first nk numbers to the back;

Step 3: Finally, copy the elements in the temporary array back.

Note: In order to ensure that the number of inversions k is less than the size of the array, the size of the array must be modulo- waited at the beginning.

void rotate(int* nums, int numsSize, int k) 
{
    k %= numsSize;
    //变长数组
    int tmp[numsSize];

    //后k个拷贝前面
    int j = 0;
    for (int i = numsSize - k; i < numsSize; ++i)
    {
        tmp[j] = nums[i];
        ++j;
    }

    //前n-k个拷贝后面
    for (int i = 0; i < numsSize - k; ++i)
    {
        tmp[j] = nums[i];
        ++j;
    }
    //拷贝回去
    for (int i = 0; i < numsSize; ++i)
    {
        nums[i] = tmp[i];
    }
}

The time complexity is: O(N).

Method 2:

This method is relatively simple and ingenious, but first you need to write an inversion function yourself,

The first step: reverse the first nk numbers;

The second step: k numbers after inversion;

The third step: the overall inversion.

Note: In order to ensure that the number of inversions k is less than the size of the array, the size of the array must be modulo- waited at the beginning.

void reverse(int* nums, int begin, int end)
{
    while (begin < end)
    {
        int tmp = nums[begin];
        nums[begin] = nums[end];
        nums[end] = tmp;
        begin++;
        end--;
    }
}
void rotate(int* nums, int numsSize, int k) 
{
    k %= numsSize;
    reverse(nums, 0, numsSize - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, numsSize - 1);
}

 The time complexity is: O(N).


This article provides two methods, and there should be other optimal solutions. You are welcome to comment below and help each other improve together.

If there are deficiencies in this article, you are welcome to comment below, and I will correct it as soon as possible.

  Old irons, remember to like and pay attention!!!

Guess you like

Origin blog.csdn.net/m0_63198468/article/details/128461731