leetcode189.轮转数组(leetcode189. Rotation array)

我用的方法是新开一个数组来保存,然后再用assign函数复制到原函数中,注意该函数void类型的,所以不能直接返回新函数。

更好的方法:

先将整个数组左右翻转,然后根据k分别反转左右两部分,用双指针进行swap

class Solution {
public:
    void reverse(vector<int>& nums, int start, int end) {
        while (start < end) {
            swap(nums[start], nums[end]);
            start += 1;
            end -= 1;
        }
    }
    void rotate(vector<int>& nums, int k) {
        k %= nums.size();
        reverse(nums, 0, nums.size() - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.size() - 1);
    }
};
————————

The method I use is to create a new array to save, and then use the assign function to copy it to the original function. Note that the function is of void type, so I can’t directly return a new function.

Better way:

First flip the whole array left and right, then reverse the left and right parts according to K, and swap with double pointers

class Solution {
public:
    void reverse(vector<int>& nums, int start, int end) {
        while (start < end) {
            swap(nums[start], nums[end]);
            start += 1;
            end -= 1;
        }
    }
    void rotate(vector<int>& nums, int k) {
        k %= nums.size();
        reverse(nums, 0, nums.size() - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.size() - 1);
    }
};